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.
ThreadPoolthreads 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.