c# - 等待线程池上的所有任务完成

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

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

我的问题是:如何防止我的控制台在后台工作完成之前终止?由于 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;
}

关于c# - 等待线程池上的所有任务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34197814/

相关文章:

c - linux fcntl 文件锁定超时

java - 在静态类中同步文件输出

c# - .NET Core 性能计数器的故事是什么?

c# - Azure 上的 HttpRuntime.AppDomainAppPath

javascript - Webbrowser控件的onclick事件

c# - 列表集合 XML 序列化

c# - 在 WinForm 应用程序中播放 MP3 文件

c# - 检测 HWND 可见性变化

C# MySQL 连接池

C#- Selenium : StaleElementReferenceException on any element on any webpage after refresh or page change