简体   繁体   English

等待ThreadPool上的所有任务完成

[英]Wait for all Tasks on the ThreadPool to finish

This might have a very simple answer, already posted here somewhere, but there is also a lot of old misleading information about threads. 这可能有一个非常简单的答案,已经在此处发布了,但是关于线程的信息还有很多旧的误导性信息。

My question is this: How do I prevent my Console from terminating before the background work is complete? 我的问题是:如何防止控制台在后台工作完成之前终止? Since the Task is created far down in the business layers of my program, I do not have access to it when the Console terminates (not like in this simple example). 由于该Task是在我的程序的业务层中很远的位置创建的,因此,当控制台终止时,我无权访问它(不同于此简单示例)。 Is there some way of awaiting all Tasks that have been created within the context of my application? 有什么方法可以等待在我的应用程序上下文中创建的所有任务?

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!");
        });
    }
}

Return the task so that you can wait on it. 返回任务,以便您可以等待它。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM