Multiple webservice call using Parallel.Foreach

I need to process multiple data retrieved from a webservice that only get me single info, like the example below:

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

What's the best approach for something like this? Would the parallel for each improve the performance or it will not be affected since i'm calling the service in the same host/port?

Upvotes: 0

Views: 2289

Answers (1)

Punit Vora
Punit Vora

Reputation: 5188

If you service is not concurrent, I think doing the parallel for each will not make much difference since calls to the service will only be handled one at a time. What you need to do is either make your service Concurrent by using something like:

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

or change the InstanceContext mode in the service behavior so that each call to the service creates a new process on the server where the service is hosted, something like

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

If you do any of these, make sure you take care of issues related to threading. More about these attributes is explained in WCF Concurrency tutorial

Upvotes: 1

Related Questions