Reputation: 943
I have two Async tasks (A & B) which upon completion will invoke the callback method passed. I want to wait till both complete and be able to perform another task C using the results of tasks A and B.
How can this be accomplished? Is there a standard way of doing this?
Any pointers will be helpful.
Upvotes: 0
Views: 122
Reputation: 75316
Use Task.WaitAll to wait tasks A and B completed.
Example:
var A = new Task<string>(DoA);
var B = new Task<string>(DoB);
A.Start();
B.Start();
Task.WaitAll(A, B);
var C = new Task(() =>
{
string resultA = A.Result;
string resultB = B.Result;
//Do something more;
}
);
C.Start();
Upvotes: 2
Reputation: 110151
use Task.WhenAll and Task.ContinueWith
var taskA = new Task<string>(DoA);
var taskB = new Task<string>(DoB);
var taskC = new Task<string>( () => DoC(taskA.Result, taskB.Result));
var taskCheckPoint = Task.WhenAll(taskA, taskB);
var taskFollowUp = taskCheckPoint.ContinueWith(taskC);
taskA.Start();
taskB.Start();
//now we return, instead of waiting.
If you don't have .net 4.5, then you have to use some form of Wait. You may not want the Task creating method to wait, so have taskC wait instead:
var taskA = new Task<string>(DoA);
var taskB = new Task<string>(DoB);
var taskC = new Task<string>( () =>{
taskA.Wait();
taskB.Wait();
DoC(taskA.Result, taskB.Result)
});
taskA.Start();
taskB.Start();
taskC.Start();
//now we return, instead of waiting.
Upvotes: 1
Reputation: 1240
There are several ways to solve this problem for example via Threading, but in C# you have techniques to implement this other ways. Therefore you have to use Delegates and an asynchronous method call.
Here is a link from Microsoft Support - if you are an experienced C# programmer you could scroll down and read the samples, else if i would recommend to read the full article.
http://support.microsoft.com/kb/315582 (sample 3 could solve your issue).
Upvotes: 1