我需要处理从网络服务中检索到的多个数据,这些数据只能获取单个信息,如下例所示:
List<string> products = GetAllProducts();
List<ProductInfo> productsInfo = new List<ProductInfo>();
using (var channel = GetClientChannel<IService>("http://localhost:51383/Service/Service.svc"))
{
Parallel.ForEach(products, product =>
{
Request myRequest = new Request();
Response myResponse = null;
try
{
myRequest.ID = product;
myResponse = channel.GetProductInfo(myRequest);
productsInfo.Add(myResponse.Info);
}
catch (Exception ex)
{
// Continue build ProductInfo list
}
});
}
DoSomething(productsInfo);
对于这样的事情,最好的方法是什么? 每个并行会改善性能还是不会受到影响,因为我在相同的主机/端口中调用服务?
答案 0 :(得分:1)
如果你的服务不是并发的,我认为对每个服务进行并行不会有太大的区别,因为对服务的调用一次只能处理一个。您需要做的是使用以下内容来提供服务Concurrent
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
class MyService : IMyService
或更改服务行为中的InstanceContext模式,以便每次调用服务都会在托管服务的服务器上创建新进程,例如
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
class MyService : IMyService
如果您执行上述任何操作,请务必注意与线程相关的问题。有关这些属性的更多信息,请参阅WCF Concurrency tutorial