下面是我的代码。
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);
}
}
每次我运行代码,都会得到不同的结果。我并不是说它们的显示顺序。
以下是我的各种结果
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
所以,为什么我不每次都显示所有三个数字。请帮忙。
最佳答案
ThreadPool
线程是background threads,这意味着一旦您的主线程结束,它们就会中止。由于没有人保证您的异步方法有机会在执行最后一条语句之前执行,因此每次都会得到不同的结果。
关于c# - 使用C#QueueUserWorkItem似乎无法执行所有方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9196987/