[英]How to process multiple 3rd party APIs without waiting for their response in ASP.NET API
Let's assume I have add order API & I need to call 3 APIs if the order is saved successfully.假设我有添加订单 API,如果订单保存成功,我需要调用 3 个 API。 I want to return the response as soon as the order processing is finished without waiting for the 3 APIs to finish.我想在订单处理完成后立即返回响应,而不用等待 3 个 API 完成。
For example:例如:
var result = ProcessOrder(parameters);
if (result.IsSuccess)
{
await SendSMSAsync(smsDetails); //All 3 APIs includes calling the API, saving status to database & log
await SendEmailAsync(emailDetails);
await ThirdPartyAsync(moreDetails);
}
return result; //I want to return this without waiting for the above 3 APIs to finish
Also, I would like to call again any failed API automatically.另外,我想再次自动呼叫任何失败的 API。 What's the best approach to achieve this?实现这一目标的最佳方法是什么?
Instead of await, create a task and call Task.Run.不要等待,而是创建一个任务并调用 Task.Run。 This will run without waiting for the task to return.这将在不等待任务返回的情况下运行。
I achieved this by using .ConfigureAwait(false)
.我通过使用.ConfigureAwait(false)
实现了这一点。 For example:例如:
if (result.IsSuccess)
{
SendSMSAsync(smsDetails).ConfigureAwait(false);
SendEmailAsync(emailDetails).ConfigureAwait(false);
ThirdPartyAsync(moreDetails).ConfigureAwait(false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.