【问题标题】:Multiple webservice call using Parallel.Foreach使用 Parallel.Foreach 的多个 Web 服务调用
【发布时间】:2014-05-04 01:42:55
【问题描述】:

我需要处理从 web 服务中检索到的多个数据,这些数据只获取我一个信息,如下例所示:

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);

这样的最佳方法是什么? 每个并行会提高性能还是不会因为我在同一个主机/端口中调用服务而受到影响?

【问题讨论】:

    标签: c# web-services parallel-processing .net-3.5


    【解决方案1】:

    如果您的服务不是并发的,我认为对每个服务进行并行处理不会有太大的不同,因为对服务的调用一次只能处理一个。您需要做的就是通过使用以下方式使您的服务Concurrent

    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
    class MyService : IMyService
    

    或更改服务行为中的InstanceContext 模式,以便每次调用服务都会在托管服务的服务器上创建一个新进程,类似于

    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
    class MyService : IMyService
    

    如果您执行其中任何一项操作,请确保您处理与线程相关的问题。有关这些属性的更多信息,请参阅WCF Concurrency tutorial

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多