简体   繁体   English

TPL内部任务

[英]TPL inner tasks

I have the following code: 我有以下代码:

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)
{
}

when rs1.Process finishes() rs5.Process()and rs6.Process() run synchronous. 当rs1.Process finish()时rs5.Process()和rs6.Process()同步运行。 How do I run them asynchronous. 我如何异步运行它们。

If I use inner tasks they are not being awaited 如果我使用内部任务,就不会等待它们

You need an inner task list: 您需要一个内部任务列表:

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());
}));

UPDATE (with TaskCreationOptions.AttachedToParent ): 更新(使用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);
}));

Exceptions should also be caught in both ways. 异常也应以两种方式捕获。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM