.NET多线程调用Web服务

时间:2019-07-12 07:18:10

标签: c# .net multithreading soap

我想提高顺序多次调用Web服务并将结果存储在列表中的过程的性能。

由于一次对WS的调用持续了1秒,因此如果我按顺序执行此工作需要300秒才能完成任务,那么我需要对Web服务进行300次调用,这就是为什么我将过程实现更改为多线程使用以下代码:

List<WCFResult> resultList= new List<WCFResult>()
using (var ws = new WCFService(binding, endpoint))
{
    foreach (var singleElement in listOfelements)
    {
         Action action = () =>
                   {                            
                        var singleResult = ws.Call(singleElement);                                 
                        resultList.Add(singleResult);        
                   };

         tasks.Add(Task.Factory.StartNew(action, TaskCreationOptions.LongRunning));
    }
}

Task.WaitAll(tasks.ToArray());

//Do other stuff with the resultList...

使用此代码,我可以为每个元素节省0.1秒的时间,这比我想象的要少,您知道我可以做进一步的优化吗?还是可以分享其他选择?

1 个答案:

答案 0 :(得分:-1)

使用以下代码,所有请求在一半的时间内得到处理

ParallelOptions ops = new ParallelOptions();
ops.MaxDegreeOfParallelism = 16;

ConcurrentBag<WCFResult> sapResultList = new ConcurrentBag<WCFResult>();

Parallel.ForEach(allItems, ops, item =>
{
        var ws = new WCFClient(binding, endpoint);
        result = ws.Call(item);
        svc.Close();
        resultList.Add(result);
});
//Do other stuff with the resultList...

任务完成。我还将结果列表修​​改为ConcurrentBag而不是List

相关问题