use*_*781 4 .net c# concurrency multithreading task-parallel-library
当我可以让父任务等待它创建的所有任务时,我不确定创建子任务有什么好处.我运行以下代码,它在两种情况下产生相同的结果.
public static void Main(string[] args)
{
RunWithChildren();
RunWithWait();
}
private static void RunWithChildren()
{
Task<Int32[]> parent = Task.Run(() =>
{
var results = new Int32[3];
new Task(r => results[0] = 0, TaskContinuationOptions.AttachedToParent).Start();
new Task(r => results[1] = 1, TaskContinuationOptions.AttachedToParent).Start();
new Task(r => results[2] = 2, TaskContinuationOptions.AttachedToParent).Start();
return results;
});
var finalTask = parent.ContinueWith(parentTask =>
{
foreach (int i in parentTask.Result)
Console.WriteLine(i);
});
finalTask.Wait();
}
private static void RunWithWait()
{
Task<Int32[]> parent = Task.Run(() =>
{
var results = new Int32[3];
Task t1 = Task.Run(() => results[0] = 0);
Task t2 = Task.Run(() => results[1] = 1);
Task t3 = Task.Run(() => results[2] = 2);
Task.WaitAll(t1, t2, t3);
return results;
});
var finalTask = parent.ContinueWith(parentTask =>
{
foreach (int i in parentTask.Result)
Console.WriteLine(i);
});
finalTask.Wait();
}
Run Code Online (Sandbox Code Playgroud)
AttachedToParent为您提供了一种构建代码的不同方法.如果孩子Task可以在父母的代码中的不同位置开始Task,使用AttachedToParent意味着您不必担心将所有孩子Task收集到一个集合中.
在实践中,我认为这Task.WaitAll()更清楚,收集Task实际上并不是一个问题,所以我几乎从不使用AttachedToParent.
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |