【问题标题】:async method for performance / throughput of web services用于 Web 服务性能/吞吐量的异步方法
【发布时间】:2015-12-17 00:04:00
【问题描述】:

我试图弄清楚在使用 HttpClient POST 到外部 api 时使用 aysnc/await 是否有助于应用程序吞吐量。

场景:我有一个类将 POST 的数据发送到支付处理器 web api。 POST 付款有 4 个步骤: 1 - 发布联系人 2 - 发布交易 3 - 邮寄捐款 4 - POST 信用卡付款

步骤 1 - 4 必须按照上面指定的顺序依次进行。

在等待来自支付处理器的响应时,我的应用程序没有任何“忙碌的工作”要做 - 在这种情况下,对以下操作使用 async/await 是否有意义?它会在大容量期间增加应用程序吞吐量吗?谢谢!

编辑:(问题被标记为不清楚) 1.我的应用是一个web api(微服务) 2.我使用.Result(阻塞)来避免异步/等待(显然这是错误的!) 3. 我们将有 1000 个请求/分钟的“峰值”负载

    public virtual ConstituentResponse PostConstituent(Constituent constituent)
    {
        var response =  PostToUrl<Constituent>("/api/Constituents", constituent);
        if (!response.IsSuccessStatusCode)
            HandleError(response);

        return response.Content.ReadAsAsync<ConstituentResponse>().Result;
    }

    public virtual TransactionResponse PostTransaction(Transaction transaction)
    {
        var response = PostToUrl<Transaction>("/api/Transactions", transaction);
        if (!response.IsSuccessStatusCode)
            HandleError(response);

        return response.Content.ReadAsAsync<TransactionResponse>().Result;
    }

    public virtual DonationResponse PostDonation(Donation donation)
    {
        var response = PostToUrl<Donation>("/api/Donations", donation);
        if (!response.IsSuccessStatusCode)
            HandleError(response);

        return response.Content.ReadAsAsync<DonationResponse>().Result;
    }

    public virtual CreditCardPaymentResponse PostCreditCardPayment(CreditCardPayment creditCardPayment)
    {
        var response = PostToUrl<CreditCardPayment>("/api/CreditCardPayments", creditCardPayment);
        if (!response.IsSuccessStatusCode)
            HandleError(response);

        return response.Content.ReadAsAsync<CreditCardPaymentResponse>().Result;
    }

    protected virtual HttpResponseMessage PostToUrl<T>(string methodUri, T value)
    {
        return _httpClient.PostAsJsonAsync(methodUri, value).Result;
    }

上面的五个方法是从另一个类/函数中调用的:

public virtual IPaymentResult Purchase(IDonationEntity donation, ICreditCard creditCard)
    {

        var constituentResponse = PostConstituent(donation);
        var transactionResponse = PostTransaction(donation, constituentResponse);
        var donationResponse = PostDonation(donation, constituentResponse, transactionResponse);
        var creditCardPaymentResponse = PostCreditCardPayment(donation, creditCard, transactionResponse);

        var paymentResult = new PaymentResult
        {
            Success = (creditCardPaymentResponse.Status == Constants.PaymentResult.Succeeded),
            ExternalPaymentID = creditCardPaymentResponse.PaymentID,
            ErrorMessage = creditCardPaymentResponse.ErrorMessage
        };

        return paymentResult;
    }

【问题讨论】:

  • 您的问题有点不清楚 - 如果您的应用程序在等待响应时没有“忙碌的工作”要做,那么您在哪里寻找性能提升?您需要显示调用Purchase 的方式以确定async 是否有帮助 - 如果您从单个线程连续调用Purchase,那么多线程会有所帮助,但如果Purchase 正在从不同的线程(即从您的网络服务器)调用,我认为它不会有帮助,因为您的 ...Async().Result 阻塞调用将允许其他线程在等待结果时运行(正如@usr 指出的那样)
  • 当您没有正确使用async 时,在“如果使用aysnc/await 将有助于提高应用程序吞吐量”中运行实验可能没有多大意义。别再打电话给.Result()了
  • @user2521118 我已经发布了一个答案,我希望我能很好地解释它并正确解决您的问题。如果没有,请告诉我。

标签: c# performance web-services async-await


【解决方案1】:

您不能在此处实际使用await Task.WhenAll,因为当您购买下一个异步操作时依赖于上一个操作的结果。因此,您需要让它们以序列化的方式执行。但是,仍然强烈建议您将async / await 用于此类 I/O,即;网络服务调用。

代码是用Async* 方法调用的消耗编写的,但实际上并没有使用该模式——它是阻塞的,可能会导致死锁以及不希望的性能影响。你应该只在控制台应用程序中使用.Result(和.Wait())。理想情况下,您应该使用async / await。这是调整代码的正确方法。

public virtual async Task<ConstituentResponse> PostConstituenAsync(Constituent constituent)
{
    var response = await PostToUrlAsync<Constituent>("/api/Constituents", constituent);
    if (!response.IsSuccessStatusCode)
        HandleError(response);

    return await response.Content.ReadAsAsync<ConstituentResponse>();
}

public virtual async Task<TransactionResponse PostTransactionAsync(Transaction transaction)
{
    var response = await PostToUrl<Transaction>("/api/Transactions", transaction);
    if (!response.IsSuccessStatusCode)
        HandleError(response);

    return await response.Content.ReadAsAsync<TransactionResponse>();
}

public virtual async Task<DonationResponse> PostDonationAsync(Donation donation)
{
    var response = await PostToUrl<Donation>("/api/Donations", donation);
    if (!response.IsSuccessStatusCode)
        HandleError(response);

    return await response.Content.ReadAsAsync<DonationResponse>();
}

public virtual async Task<CreditCardPaymentResponse> PostCreditCardPaymentAsync(CreditCardPayment creditCardPayment)
{
    var response = await PostToUrlAsync<CreditCardPayment>("/api/CreditCardPayments", creditCardPayment);
    if (!response.IsSuccessStatusCode)
        HandleError(response);

    return await response.Content.ReadAsAsync<CreditCardPaymentResponse>();
}

protected virtual Task<HttpResponseMessage> PostToUrlAsync<T>(string methodUri, T value)
{
    return _httpClient.PostAsJsonAsync(methodUri, value);
}

用法

public virtual await Task<IPaymentResult> PurchaseAsync(IDonationEntity donation, ICreditCard creditCard)
{
    var constituentResponse = await PostConstituentAsync(donation);
    var transactionResponse = await PostTransactionAsync(donation, constituentResponse);
    var donationResponse = await PostDonationAsync(donation, constituentResponse, transactionResponse);
    var creditCardPaymentResponse = await PostCreditCardPaymentAsync(donation, creditCard, transactionResponse);

    var paymentResult = new PaymentResult
    {
        Success = (creditCardPaymentResponse.Status == Constants.PaymentResult.Succeeded),
        ExternalPaymentID = creditCardPaymentResponse.PaymentID,
        ErrorMessage = creditCardPaymentResponse.ErrorMessage
    };

    return paymentResult;
}

【讨论】:

  • 好点! async/await 确实是一种模式,代码应该从请求级别/控制器级别修改为异步..
【解决方案2】:

首先,现在编写代码的方式根本没有帮助,因为您一直在通过调用Result 阻塞。如果这是一件好事,为什么不所有的 API 都在内部为你做这件事?!你不能用异步作弊......

只有在超过 100 个线程范围内发生的线程池能力时,您才会看到吞吐量增加。

他需要的平均线程数是requestsPerSecond * requestDurationInSeconds。插入一些数字,看看这对你来说是否现实。

我将把我的标准帖子链接到你是去同步还是异步,因为我觉得你并没有绝对清楚什么时候异步 IO 是合适的。

https://stackoverflow.com/a/25087273/122718 为什么 EF 6 教程使用异步调用? https://stackoverflow.com/a/12796711/122718我们应该切换到默认使用异步 I/O 吗?

一般情况下,等待时间较长,并行请求较多时比较合适。

我的应用程序在等待响应时没有任何“忙碌的工作”要做

其他进来的请求太忙了。

请注意,当线程被阻塞时,CPU 也不会被阻塞。另一个线程可以运行。

【讨论】:

  • 是的,其他请求也很重要,这就是我担心 .Result 并试图弄清楚如何使用 async/await 的原因。如果 POST 信用卡需要 2 秒,那么当前线程会被释放以处理其他请求吗? (使用异步/等待)
  • 是的,使用 async 并等待一切。
【解决方案3】:

当你在做 async/await 时,你应该整天异步。 阅读Async/Await - Best Practices in Asynchronous Programming

你需要让它们异步返回

 public virtual async Task ConstituentResponse PostConstituent(Constituent constituent)
{
    var response =  PostToUrl<Constituent>("/api/Constituents", constituent);
    if (!response.IsSuccessStatusCode)
        HandleError(response);

    return await response.Content.ReadAsAsync<ConstituentResponse>();
}
//...
//etc

然后从主函数

  await Task.WhenAll(constituentResponse, transactionResponse, donationResponse, creditCardPaymentResponse);

编辑:误读 OP。不要将 await Task.WhenAll 用于同步调用

【讨论】:

  • 有趣.. Task.WhenAll 是否按顺序执行 4 个调用,因为这些调用依赖于上一步中调用的数据..
  • 很好的答案,但是是的,因为 OP 的方法相互依赖,Task.WhenAll() 可以说不适合这里
  • @Micky 是的,你是对的。我忽略了OP。是的,它们必须按顺序执行,并且以异步方式执行它们并没有真正的好处。
  • 约旦,好点子。 @user2521118 目前尚不清楚从客户端等待一系列相关且连续的“异步”调用的角度来看您会得到什么好处
  • @Micky 和 ​​joordan831 - 这也是我编写代码时的想法。 “阻塞”这个词让我害怕,但我最终使用了 HttpClient 类,因为它可以轻松地将业务对象序列化到 JSON 或从 JSON 序列化。假设 .Result 与同步代码相同是否安全?只要它不阻塞其他线程,一切都很好..我们将通过更多的硬件/负载平衡进行扩展以处理高容量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 2011-06-29
  • 1970-01-01
  • 2012-10-23
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多