等待ThreadPool上的所有任务完成

时间:2015-12-10 09:18:01

标签: c# .net multithreading asp.net-4.5

这可能有一个非常简单的答案,已在某处发布,但也有很多关于线程的误导性信息。

我的问题是:在后台工作完成之前,如何阻止我的控制台终止?由于Task是在我的程序的业务层中创建的,所以当Console终止时我无法访问它(不像在这个简单的例子中)。有没有办法等待在我的应用程序上下文中创建的所有任务?

public class Program
{
    private static void Main(string[] args)
    {
       DoBackgroundWork();
       System.Console.WriteLine("Doing something else during background work");

       // Wait for all created Tasks to complete before terminating
       ???
    }

    private static void DoBackgroundWork()
    {
        var task = Task.Run(() =>
        {
            System.Console.WriteLine("Starting background work");
            Thread.Sleep(10000);
            System.Console.WriteLine("Background work finished!");
        });
    }
}

1 个答案:

答案 0 :(得分:3)

返回任务,以便您可以等待它。

private static void Main(string[] args)
{
    var task = DoBackgroundWork();
    System.Console.WriteLine("Doing something else during background work");

    // Wait for all created Tasks to complete before terminating
    task.Wait();
}

private static Task DoBackgroundWork()
{
    var task = Task.Run(() =>
    {
        System.Console.WriteLine("Starting background work");
        Thread.Sleep(1000);
        System.Console.WriteLine("Background work finished!");
    });

    return task;
}