如何在C#中与Web服务并行发出多个请求 [英] How to make Multiple requests in parallel to a webservice in C#

查看:106
本文介绍了如何在C#中与Web服务并行发出多个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要按以下方式致电3个WCF服务

I need to call 3 WCF services as below,

var client = new WebClient();
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    var resultJson1 = client.UploadString("http://localhost:45868/Product/GetAvailableProductsByContact",
                                         jsonser1);
var resultJson2= client.UploadString("http://localhost:45868/Product/GetMemberProductsByContact",
                                         jsonser2);

var resultJson3= client.UploadString("http://localhost:45868/Product/GetCoachProductsByContact",
                                         jsonser3);

这需要大量时间才能获得结果并显示在页面上.谁能帮助我如何并行执行它们?

This takes a lot of time to get results and display on the page. Can anyone help me how I could execute them in parallel?

推荐答案

您可以使用

或者,由于您的请求都非常相似,仅URL和上载字符串不同,因此您可以使用LINQ AsParallel数组处理:

Or alternatively, since your requests are all very similar, differing only by the url and upload string, you can use LINQ AsParallel array processing:

var requests = new [] {
    new { Url = "http://localhost:45868/Product/GetAvailableProductsByContact", Input = jsonser1 },
    new { Url = "http://localhost:45868/Product/GetMemberProductsByContact", Input = jsonser2 },
    new { Url = "http://localhost:45868/Product/GetCoachProductsByContact", Input = jsonser3 },
};
var result = requests.AsParallel().Select(req => {
    var client = new WebClient();
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    var json = client.UploadString(req.Url, req.Input);
    return json;
}).ToArray();

// when above code has finished running, all tasks are completed
var resultJson1 = result[0];
var resultJson2 = result[1];
var resultJson3 = result[2];

这篇关于如何在C#中与Web服务并行发出多个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆