使用c#QueueUserWorkItem不';我似乎无法执行所有的方法

使用c#QueueUserWorkItem不';我似乎无法执行所有的方法,c#,multithreading,C#,Multithreading,下面是我的代码 class Program { static void Main(string[] args) { Console.WriteLine("Main thread starts and sleeps"); Student stu = new Student(); ThreadPool.QueueUserWorkItem(stu.Display, 7); ThreadPool.QueueUserWorkI

下面是我的代码

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

那么,为什么每次我都不显示这三个数字呢。请帮助。

这是因为您没有等待任务完成。它们排队等待在线程池上执行,但主线程在全部或部分线程完成之前退出

要看到所有这些都完成,您需要在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");
    }
}

不幸的是,C#没有
线程池
的内置屏障,因此您需要自己实现一个,或者使用不同的构造,如
并行。调用
线程池
线程,这意味着一旦主线程结束,它们就会中止。由于没有人保证您的异步方法有机会在最后一条语句之前执行,因此每次都会得到不同的结果。

或使用任务。这些天我发现自己用任务替换了所有的线程池结构。谢谢Groo。我只是在学习各种线程方法时使用了ThreadPool。@Muthukumar:很好,但请注意,虽然我试图解释为什么会发生这种情况,但通常您仍然希望知道任务何时完成,因此您当然应该在完成后让您的后台任务发出信号(或使用.NET 4任务)。谢谢。我猜这个信号一定和AutoResetEvent中的一样。@Muthukumar:如果你需要等待多个线程,那么你需要一个
AutoResetEvent
s的列表,并需要等待所有线程都被发送信号。您也可以使用不同的构造(例如信号量)来实现这一点,但在.NET4中,最简单的方法是使用
Parallel
类,该类本身完成大部分工作。关于线程的一个很好的资源是,如果您想更深入地了解实际情况,我建议您彻底阅读它。对于
任务
,这些概念中的许多对您来说都是隐藏的。