Reputation: 9579
Below is my code.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main thread starts and sleeps");
Student stu = new Student();
ThreadPool.QueueUserWorkItem(stu.Display, 7);
ThreadPool.QueueUserWorkItem(stu.Display, 6);
ThreadPool.QueueUserWorkItem(stu.Display, 5);
Console.WriteLine("Main thread ends");
}
}
public class Student
{
public void Display(object data)
{
Console.WriteLine(data);
}
}
Every time I run the code, i get different results. I do not mean the order in which they are displayed.
Following are my various results
Main thread starts and sleeps
Main thread ends
Main thread starts and sleeps
Main thread ends
7
5
6
Main thread starts and sleeps
Main thread ends
7
So, why don't i get all three numbers displayed every time. Please help.
Upvotes: 2
Views: 2528
Reputation: 51224
ThreadPool
threads are background threads, meaning they are aborted once your main thread ends. Since no one guarantees that your async methods will have a chance to execute before the last statement, you will get different results each time.
Upvotes: 3
Reputation: 62439
That's because you are not waiting for the tasks to finish. They get queued to be executed on the thread pool, but the main thread exits before all or some of them have completed.
To see all of them finishing you need a synchronization barrier before the end of Main:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main thread starts and sleeps");
Student stu = new Student();
ThreadPool.QueueUserWorkItem(stu.Display, 7);
ThreadPool.QueueUserWorkItem(stu.Display, 6);
ThreadPool.QueueUserWorkItem(stu.Display, 5);
// barrier here
Console.WriteLine("Main thread ends");
}
}
Unfortunately, C# does not have a built-in barrier for ThreadPool
, so you will need to either implement one yourself, or use a different construct, like Parallel.Invoke
.
Upvotes: 5