c# - 如何正确设置 HttpClient 的延续?

标签 c# asp.net-web-api .net-4.0 task-parallel-library httpclient

我使用的是 .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/

相关文章:

c# - WebAPI One Asp.Net (ASP5/vNext) 中的分页

asp.net-mvc-4 - 你必须调用 "WebSecurity.InitializeDatabaseConnection"... 但我已经有了

c# - 将 WPF 项目从 3.5 迁移到 4.0 后,什么可能导致性能下降?

c# - 调试时显示奇怪的对象成员

c# - 自定义 DataAnnotation IsValid 未调用

c# - 为什么 Fiddler 会修复我与 WCF 服务器的连接问题?

asp.net-web-api - 使用JWT在Asp.net Web API上实现身份验证

c# - 从 WPF 对话框返回自定义值

c# - 带有 docker microsoft/iis 的卷

c# - 使用 async/await 和 TaskCompletionSource 的奇怪堆栈跟踪增长