2

I'm a bit confused how should I implement worklflow of multiple asynchronous tasks. For example - Task1 started, when Task1 completed, Task2 started, when Task2 completed start TaskN etc.
Or another words - how asynchronous task may notify "parent" task about his status? I suppose can use here TaskStatus but not sure how exactly. I did searched on MSDN but there is no complete example of such pattern.
P.S. I edit my question in order to concentrate on one specific question.

andrey.shedko
  • 3,128
  • 10
  • 61
  • 121
  • I didn't downvote, but you've asked a few things that could each be their own question because each requires a fairly in depth answer. Executing several tasks in parallel: http://stackoverflow.com/q/12337671/84206 Exception handling: http://msdn.microsoft.com/en-us/library/dd537614(v=vs.110).aspx There are lots of other variations though: http://stackoverflow.com/questions/tagged/async-await – AaronLS Jan 03 '15 at 02:43

1 Answers1

5

If you truly want to wait to start task2 until after task1 completes, one way would be like this:

Task<string> task1 = GetUsername();
string username = await task1; // blocks(or "waits") here until GetUsername returns

Task<string> task2 = GetConfig(username); // since we have the return from above, we can pass it here
string config = await task2 ; // blocks here until GetConfig returns

Note in this Task1 and Task2 do not execute in parallel with each other, since we explicitly wait for one to complete before starting the other, as you requested. Though they are async relative to the thread calling them.

If you had a List<Task> and wanted to execute them sequentially then the approach would be different, and executing them in parallel would be yet a different approach.

If you look around stackoverflow you'll see alot of examples of using some of the methods such as Wait, WaitAll, WhenAll, etc. that can allow you to do alot of varied combinations of things.

AaronLS
  • 37,329
  • 20
  • 143
  • 202