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) .
source share