andrey.shedko
andrey.shedko

Reputation: 3238

Asynchronous pattern - run task when previous task completed

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.

Upvotes: 2

Views: 163

Answers (1)

AaronLS
AaronLS

Reputation: 38364

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.

Upvotes: 5

Related Questions