【发布时间】:2014-09-18 18:48:02
【问题描述】:
我使用的是 .NET 4.0,所以不能使用 async/await 关键字。
在我费力地设置任务和延续而不是仅仅调用 .Result 之后,我的努力得到的只是一团糟,它在几十个 HTTP GET 的工作负载上运行速度慢了 46%。 (如果我在串行或并行循环中调用工作负载,我会得到类似的性能下降)
我必须做什么才能看到任何性能优势?
//Slower code
public UserProfileViewModel GetAsync(Guid id)
{
UserProfileViewModel obj = null;//Closure
Task result = client.GetAsync(id.ToString()).ContinueWith(responseMessage =>
{
Task<string> stringTask = responseMessage.Result
.Content.ReadAsStringAsync();
Task continuation = stringTask.ContinueWith(responseBody =>
{
obj = JsonConvert
.DeserializeObject<UserProfileViewModel>(responseBody.Result);
});
//This is a child task, must wait before returning to parent.
continuation.Wait();
});
result.Wait();
return obj;
}
//Faster code
public UserProfileViewModel GetSynchr(Guid id)
{
//Asych? What's is that?
HttpResponseMessage response = client.GetAsync(id.ToString()).Result;
string responseBody = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<UserProfileViewModel>(responseBody);
}
【问题讨论】:
标签: c# asp.net-web-api .net-4.0 task-parallel-library httpclient