I just started using the TPL, and I want to make several calls to web services happen in parallel. From what I can gather, I see two ways of doing this.
Either Parallel.ForEach:
List<ServiceMemberBase> list = new List<ServiceMemberBase>(); //Take list from somewhere.
Parallel.ForEach(list, member =>
{
var result = Proxy.Invoke(member);
//...
//Do stuff with the result
//...
});
Or Task<T>:
List<ServiceMemberBase> list = new List<ServiceMemberBase>(); //Take list from somewhere.
ForEach(var member in list)
{
Task<MemberResult>.Factory.StartNew(() => proxy.Invoke(member));
}
//Wait for all tasks to finish.
//Process the result objects.
Disregarding if the syntax is correct or not, are these to equivilant?
Will they produce the same result? If not, why? and which is preferable?
For the code and use case you discuss, the two approaches are essentially equivalent.
Parallel.ForEach is useful when you have to partition an input range over several tasks (not applicable here), or is easier to synchronize the merging of results of several independent parallel operations (perhaps applicable here?).
In any case, you’ve correctly noted that in the Parallel.ForEach case, you don’t have to manually synchronize the wait for completion, whereas if you manually start tasks, you do have to manage that synchronization yourself. In this case you would probably use something like
Task.WaitAll(...).