[英]How to make Multiple requests in parallel to a webservice in C#
我需要按以下方式致电3个WCF服务,
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);
这需要大量时间才能获得结果并显示在页面上。 谁能帮助我如何并行执行它们?
您可以使用任务并行性库 :
Task<string>[] taskArray = new Task<string>[]
{
Task.Factory.StartNew(() => {
var client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var json = client.UploadString("http://localhost:45868/Product/GetAvailableProductsByContact",
jsonser1);
return json;
}),
Task.Factory.StartNew(() => {
var client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var json = client.UploadString("http://localhost:45868/Product/GetMemberProductsByContact",
jsonser2);
return json;
}),
Task.Factory.StartNew(() => {
var client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var json = client.UploadString("http://localhost:45868/Product/GetCoachProductsByContact",
jsonser3);
return json;
}),
};
// the request for .Result is blocking and waits until each task
// is completed before continuing; however, they should also all
// run in parallel instead of sequentially.
var resultJson1 = taskArray[0].Result;
var resultJson2 = taskArray[1].Result;
var resultJson3 = taskArray[2].Result;
或者,由于您的请求非常相似,仅URL和上载字符串不同,因此可以使用LINQ AsParallel
数组处理:
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];
您可以使用开始/结束模式:
本示例说明如何并行调用两个ws。 您可以将其扩展到N个服务。
尝试创建一个执行您的每个调用的Task
( MSDN )
您可以尝试执行以下操作
首先为每个调用创建一个Task<String>
var client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
Task<String> task1 = Task.Factory.StartNew(() => {
client.UploadString("http://localhost:45868/Product/GetAvailableProductsByContact",
jsonser1);
});
冲洗并重复其他2次
之后,您可以通过调用task1.Value
, task2.Value
和task3.Value
并返回一个String
来加入3 Task<String>
的执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.