TPL内部任务

时间:2017-08-29 07:21:26

标签: c# .net task-parallel-library

我有以下代码:

List<Task> tasks = new List<Task>();

tasks.Add(Task.Factory.StartNew(() =>
{
    rs1.Process();
}).ContinueWith((previousTask) =>
{
    rs5.Process();
    rs6.Process();
}));

tasks.Add(Task.Factory.StartNew(() =>
{
    rs2.Process();
}));

tasks.Add(Task.Factory.StartNew(() =>
{
    rs3.Process();
}));

try
{
    Task.WaitAll(tasks.ToArray());
}
catch (AggregateException e)
{
}

当rs1.Process结束时()rs5.Process()和rs6.Process()运行同步。如何异步运行它们。

如果我使用内部任务,则无法等待

1 个答案:

答案 0 :(得分:0)

您需要一个内部任务列表:

tasks.Add(Task.Factory.StartNew(() =>
{
    rs1.Process();
}).ContinueWith((previousTask) =>
{
    List<Task> loInnerTasks = new List<Task>();
    loInnerTasks.Add(Task.Run(() => rs5.Process()));
    loInnerTasks.Add(Task.Run(() => rs6.Process()));
    Task.WaitAll(loInnerTasks.ToArray());
}));

更新(使用TaskCreationOptions.AttachedToParent):

tasks.Add(Task.Factory.StartNew(() =>
{
    rs1.Process();
}).ContinueWith((previousTask) =>
{
    Task.Factory.StartNew(() => rs5.Process(), TaskCreationOptions.AttachedToParent);
    Task.Factory.StartNew(() => rs6.Process(), TaskCreationOptions.AttachedToParent);
}));

也应该以两种方式捕获例外情况。