繁体   English   中英

如何正确设置HttpClient的延续?

[英]How do I set up the continuations for HttpClient correctly?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM