Reputation: 55
I have one doubt. I implemented my wcf 4.0 service method as shown below.
IAsyncResult BeginGetData(string userid, AsyncCallback cb, object asyncState)
{
// Here i want to call 2 different methods simultaneously of another class
// string result1 = classA.Method1(userid);
// string result2 = classA.Method2(userid);
}
How I can call 2 methods simultaneously and both result values send back to client in the same return method ? Can we do it using TPL ? In TPL, if we use Task.ContinueWith, it will run sequentially. Is there any way that run those 2 methods parallely and return the 2 results through the EndGetData method ? If Method1 is completing first, then it should wait for Method2 to complete. Or another way is to fireback each method result as and when they completed. Is this possible ? Please help and guide me.
Upvotes: 0
Views: 1180
Reputation: 23831
I am not sure about the intracacies of using WCF to do all of this for you. However, here you can just use Task Parallel Library's (TPL) ContinueWhenAll
keyword:
An example of its usage is
Task task1 = Task.Factory.StartNew(() => Console.WriteLine("X"));
Task task2 = Task.Factory.StartNew(() => Console.WriteLine("Y"));
this fires the two task off concurrently on two seperate background thread-pool threads. You can then wait for both to finish using
var continuation = Task.Factory.ContinueWhenAll(
new[] { task1, task2 }, tasks => Console.WriteLine("Done!"));
Or here, you could also use the WhenAll
task combinator and write
var continuation = Task.WhenAll(task1, task2)
.ContinueWith(ant => Console.Writeline("Done!"));
Example in your case of returning data from the tasks:
Task<int> task1 = Task.Factory.StartNew<int>(() =>
{
return SomeSerialMethodReturningInt32A();
});
Task<int> task2 = Task.Factory.StartNew<int>(() =>
{
return SomeSerialMethodReturningInt32B();
});
then in the continuation (what ever method of continuation you choose), you can query the results (and remember to observe your AggregateException
s) as follows
var continuation = Task.Factory.ContinueWhenAll(
new[] { task1, task2 }, tasks =>
{
int i = task1.Result;
int j = task2.Result;
// Neglecting exception handling.
});
See this CodeProject article for a great introduction to TPL.
I hope this helps.
Upvotes: 1