【发布时间】: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