Вы можете использовать библиотеку параллелизма задач :
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-адресом и строкой загрузки, вы можете использовать LINQAsParallel
обработка массива:
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];