嗯,首先,请记住,你已经有了一个异步问题就在这里:
HttpContent httpContent = new FormUrlEncodedContent(postData);
// whoops! .Result makes this line synchronous.
HttpResponseMessage response = client.PostAsync("/mydata", httpContent).Result;
var responsecode = (int)response.StatusCode;
if (response.IsSuccessStatusCode)
{
var responseBodyAsText = await response.Content.ReadAsStringAsync();
return responseBodyAsText;
}
else
{
return responsecode +" " +response.ReasonPhrase;
}
其次,由于HttpClient
给你一个Task<HttpResponseMessage>
,好像你想要把所有的回答作为字符串,比如说Task<IEnumerable<string>>
,对吧?我们可以很容易地编写一个函数把Task<HttpResponseMessage>
为Task<string>
:
public async Task<string> ReadResultAsync(Task<HttpResponseMessage> responseTask)
{
var response = await responseTask;
var responsecode = (int)response.StatusCode;
if (response.IsSuccessStatusCode)
{
var responseBodyAsText = await response.Content.ReadAsStringAsync();
return responseBodyAsText;
}
else
{
return responsecode + " " + response.ReasonPhrase;
}
}
现在让我们假设你有后的一些数据收集,你需要转成字符串这个异步集合,称为myData
:
// bear in mind, this code doesn't (necessarily) need to be in a
// method marked "async". If you want to await on resultsTask, though,
// it would need to be in an async method.
var tasks = myData
.Select(x => new FormUrlEncodedContent(x)) // IEnumerable<FormUrlEncodedContent>
.Select(x => client.PostAsync("/mydata", x)) // IEnumerable<Task<HttpResponseMessage>>
.Select(x => ReadResultAsync(x)) // IEnumerable<Task<string>>
.ToArray(); // Task<string>[]
var resultsTask = Task.WhenAll(tasks); // here is Task<string[]>
来源
2015-11-18 19:53:15
FMM
Hi FMM When I调用var tasks = myData。选择...它是否需要在parallel.foreach循环或简单的foreach循环中?然后在循环结束后调用var resultsTask = Task ... – Steve
没有理由使用并行foreach循环,除非在该集合中有足够的项目需要将它们分发到多个核心。 – FMM
你好,你能够更详细地概述你如何建立链接声明?另外,主要优先级,可以调用var本身不是异步的方法调用var resulsTask? (以避免一连串的方法成为异步!)Ta – Steve