我使用的是 .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);
}
最佳答案
您正在使用“异步”方法,但同步执行所有操作。这肯定不会比使用同步方法同步执行所有操作更好。
看看这个:
public Task<UserProfileViewModel> GetAsync(Guid id)
{
var uri = id.ToString();
return client.GetAsync(uri).ContinueWith(responseTask =>
{
var response = responseTask.Result;
return response.Content.ReadAsStringAsync().ContinueWith(jsonTask =>
{
var json = jsonTask.Result;
return JsonConvert.DeserializeObject<UserProfileViewModel>(json);
});
}).Unwrap();
}
注意该方法如何返回 Task
并从该方法返回延续。这允许您的方法几乎立即返回,为调用者提供正在运行的工作的句柄和任何需要发生的延续。返回的任务只有在一切都完成后才会完成,结果将是你的 UserProfileViewModel
.
Unwrap
方法需要一个 Task<Task<UserProfileViewModel>>
并将其变成 Task<UserProfileViewModel>
.
关于c# - 如何正确设置 HttpClient 的延续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25920205/