任务并行库 - 知道所有任务何时完成 [英] Task Parallel Library - Know when all tasks are finished
问题描述
我使用任务并行库来启动一些任务,如下所示:
public static void Main()
{
for(var i = 0; i <10; i ++)
{
var x = i;
Task.Factory.StartNew(()=> new WorkerClass(x).Do());
}
//(*)这里我想等待所有任务完成
Task.WaitAll();
Console.WriteLine(Ready。);
Console.ReadLine();
}
问题是某些任务可以自己创建新任务。这是 WorkerClass
的样子:
public class WorkerClass
{
private static readonly NLog.Logger Log = NLog.LogManager.GetCurrentClassLogger();
private readonly int _i;
public WorkerClass(int i)
{
_i = i;
}
public void Do()
{
if(_i%3 == 0)
Task.Factory.StartNew(()=> ; new WorkerClass(_i + 101).Do());
Log.Info(Started {0},_i);
Thread.Sleep(2000);
Log.Info(Done {0},_i);
}
}
对于 i
我希望能等到所有任务(包括那些任务)
有没有干净/内置的方法来做这个(有或没有TPL)?
保留对所有顶级任务的引用,然后使用 WaitAll
:
var tasks = new Task [10];
for(var i = 0; i <10; i ++)
{
var x = i;
tasks [i] = Task.Factory.StartNew(()=> new WorkerClass(x).Do());
}
Task.WaitAll(tasks);
对于子任务,只要确保将它们附加到父任务。这意味着父任务在所有子任务也完成之前不会进入完整状态。
Task.Factory.StartNew (()=> {},TaskCreationOptions.AttachedToParent);
I use Task Parallel Library to start some tasks, like so:
public static void Main()
{
for (var i = 0; i < 10; i++)
{
var x = i;
Task.Factory.StartNew(() => new WorkerClass(x).Do());
}
// (*) Here I'd like to wait for all tasks to finish
Task.WaitAll();
Console.WriteLine("Ready.");
Console.ReadLine();
}
The problem is that some tasks can create new tasks themselves. This is how WorkerClass
looks like:
public class WorkerClass
{
private static readonly NLog.Logger Log = NLog.LogManager.GetCurrentClassLogger();
private readonly int _i;
public WorkerClass(int i)
{
_i = i;
}
public void Do()
{
if (_i % 3 == 0)
Task.Factory.StartNew(() => new WorkerClass(_i + 101).Do());
Log.Info("Started {0}", _i);
Thread.Sleep(2000);
Log.Info("Done {0}", _i);
}
}
For every value of i
that's a multiple of 3, a new Task is started.
I'd like to be able to wait until all tasks (including the ones created by other tasks) are finished.
Is there a clean/built-in way to do this (with or without TPL)?
Keep a reference to all top-level tasks and then just use WaitAll
:
var tasks = new Task[10];
for (var i = 0; i < 10; i++)
{
var x = i;
tasks[i] = Task.Factory.StartNew(() => new WorkerClass(x).Do());
}
Task.WaitAll( tasks );
As for the child tasks, just make sure you attach them to the parent task. This means that the parent task will not go into a complete state until all child tasks are also finished.
Task.Factory.StartNew(() => { }, TaskCreationOptions.AttachedToParent);
这篇关于任务并行库 - 知道所有任务何时完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!