.NET Framework 4.0: task chain in a loop

I want to bind several Task s so that when the next run finishes. I know I can do this using ContinueWith . But what if I have a large number of tasks, so that:

t1 continues with t2

t2 continues with t3

t3 continues with t4

...

Is there a good way to do this other than creating this chain manually using a loop?

+4
source share
2 answers

Well, if you have any enumerated Action delegates or something you want to do, you can easily use LINQ to do the following:

 // Create the base task. Run synchronously. var task = new Task(() => { }); task.RunSynchronously(); // Chain them all together. var query = // For each action from action in actions // Assign the task to the continuation and // return that. select (task = task.ContinueWith(action)); // Get the last task to wait on. // Note that this cannot be changed to "Last" // because the actions enumeration could have no // elements, meaning that Last would throw. // That means task can be null, so a check // would have to be performed on it before // waiting on it (unless you are assured that // there are items in the action enumeration). task = query.LastOrDefault(); 

The above code is really your loop, only in a more favorable form. It does the same in that it performs the previous task (after refueling using the fictitious "noop" Task ), and then adds a continuation in the form of ContinueWith (assigning a continuation to the current task in the process for the next iteration of the loop that is executed when LastOrDefault called) .

+6
source

You can use ContinueWhenAll static extensions here .

This way you can transfer multiple tasks.


Update

You can use a chain extension, for example:

 public static class MyTaskExtensions { public static Task BuildChain(this Task task, IEnumerable<Action<Task>> actions) { if (!actions.Any()) return task; else { Task continueWith = task.ContinueWith(actions.First()); return continueWith.BuildChain(actions.Skip(1)); } } } 
+3
source

Source: https://habr.com/ru/post/1345872/


All Articles