我刚开始使用 TPL,我想同时调用多个 Web 服务。据我所知,我看到了两种方法。
要么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
//...
});
或者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.
不管语法是否正确,这些是等价的吗?
它们会产生相同的结果吗?如果不是,为什么?哪个更可取?