There are two approcahes that come to my mind.
A. The way you are doing it now but using continuations ContinueWith
/ContinueWhenAll
as described in this answer and in this articale. So for your case you might use a single continuation using child tasks, so
TaskCreationoptions op = TaskCreationOptions.AttachedToParent;
Task.Factory.StartNew(() =>
{
var task1 = Task.Factory.StartNew (CallService(1));
var task2 = Task.Factory.StartNew (CallService(2));
var task3 = Task.Factory.StartNew (CallService(3));
})
.ContinueWith(ant => { SomeOtherselegate });
Or you could chain the continuations as explained here.
Another way is to use ContinueWhenAll
.
var task1 = Task.Factory.StartNew (CallService(1));
var task2 = Task.Factory.StartNew (CallService(2));
var task3 = Task.Factory.StartNew (CallService(3));
var continuation = Task.Factory.ContinueWhenAll(
new[] { task1, task2, task3 }, tasks => Console.WriteLine("Done!"));
The only thing to think about here is the way you can have a variable number of tasks, but this is easy and I will let you work that one out.
B. The other way is to use .NET4.5+ and async
/await
. So your code would be something like
private async void CallAllServicesAsync()
{
await CallServiceAsync(1);
await CallServiceAsync(2);
await CallServiceAsync(3);
}
where
private Task CallServiceAsync(int serviceNumber)
{
return Task.Run(() = > { SomeMethod(); });
}
The above is equivelent to the first code shown but the framework takes care of everything for you under-the-hood.
I hope this helps.