【问题标题】:How do I set up the continuations for HttpClient correctly?如何正确设置 HttpClient 的延续?
【发布时间】: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


    【解决方案1】:

    您正在使用“异步”方法,但所有事情都是同步进行的。这当然不会比使用同步方法同步完成所有事情更好。

    看看这个:

    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&lt;Task&lt;UserProfileViewModel&gt;&gt; 并将其转换为 Task&lt;UserProfileViewModel&gt;

    【讨论】:

    • 您的 Unwrap 方法的实现非常糟糕,尤其是考虑到 .NET 中有一个可以正确执行的实现。
    • @Servy 我错误地认为它只存在于 .NET 4.5 中。我删除了快速而肮脏的实现,因为它在 .NET 4.0(OP 要求的版本)中。
    • 即使是这样,您的实现仍然依赖于 .NET 4.5 方法。
    • 这样比较像,比串口快5倍,比调用.Result快2倍。
    • @MatthewMartin 很高兴能帮上忙。 :) 通常任何对Wait()Result 的调用都会阻塞当前线程,这表明异步编码是错误的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多