gpt4 book ai didi

c# - 如何在 C# 中向 Web 服务并行发出多个请求

转载 作者:太空宇宙 更新时间:2023-11-03 19:24:30 25 4
gpt4 key购买 nike

我需要如下调用 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 parallelism library :

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

关于c# - 如何在 C# 中向 Web 服务并行发出多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9844203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com