【发布时间】:2020-04-06 06:20:21
【问题描述】:
我是 .NET 任务和异步编码的新手,所以我想知道在我的情况下我应该做什么:
我有一个接收 XML 文件的 .NET Core WebApi,它充当以下过程的触发器:
- 我需要进程在“后台”运行,所以我的意思是 API 调用者应该立即得到响应,然后进程应该运行
- 我需要将 XML 解析为一个对象
- 有了这些数据,我需要联系 3 个 API
- 如果这些 API 中的任何一个没有响应或未能检索到所需的数据,我们需要停止并记录此情况
- 如果检索到所有数据,我需要对这些数据进行计算(从数据库中获取一些数据并使用 API 和数据库数据进行计算)
-
计算完成后,我需要发送电子邮件并联系另一个 API
7.最重要的是:由于 AppRecycle,我对此是否安全?
这只是为了解释我的情况,所以我有以下内容:
[HttpPost]
public async Task<JsonResult> DepositAsync([FromBody] Taa message){
try
{
Api1Response api1Response = await this.GetApiData1();
Api1Response api2Response = await this.GetApiData2();
// If all of this was successful, do the calculation
CalculationResult result = await this.CalculateAsync(api1Response, api2Response);
// Notify
await Notify(result);
}
catch (Exception ex)
{
Log.Error($"Something went wrong: {ex.Message}", ex);
throw;
}
return new JsonResult(new ApiResponse<string>(requestId.ToString(), Response, StatusCodes.Status200OK) { Data = "Success" });
}
我现在的问题:
- 什么时候需要使用 Task.Run(() => {});在GetApiData1()、GetApiData2()方法里面,做Http调用?
- 我需要在 Task.Run(() => {}) 中调用 GetApi 方法吗? ?
- 一般来说,什么时候需要使用Task.Run,什么时候不需要?
或者我只需要这样做:
[HttpPost]
public async Task<JsonResult> DepositAsync([FromBody] Taa message){
try
{
Task.Run(() => {
Api1Response api1Response = await this.GetApiData1();
Api1Response api2Response = await this.GetApiData2();
// If all of this was successful, do the calculation
CalculationResult result = await this.CalculateAsync(api1Response, api2Response);
// Notify
await Notify(result);
});
}
catch (Exception ex)
{
Log.Error($"Something went wrong: {ex.Message}", ex);
throw;
}
return new JsonResult(new ApiResponse<string>(requestId.ToString(), Response, StatusCodes.Status200OK) { Data = "Success" });
}
非常感谢!
【问题讨论】:
标签: .net asp.net-core asynchronous task-parallel-library