簡體   English   中英

等待ThreadPool上的所有任務完成

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

這可能有一個非常簡單的答案,已經在此處發布了,但是關於線程的信息還有很多舊的誤導性信息。

我的問題是:如何防止控制台在后台工作完成之前終止? 由於該Task是在我的程序的業務層中很遠的位置創建的,因此,當控制台終止時,我無權訪問它(不同於此簡單示例)。 有什么方法可以等待在我的應用程序上下文中創建的所有任務?

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

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

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