简体   繁体   中英

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. 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 ):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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