这可能有一个非常简单的答案,已经发布在此处的某个地方,但也有很多关于线程的旧的误导性信息。
我的问题是:如何防止我的控制台在后台工作完成之前终止?由于 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/