我正在ASP.NET中实现一个REST API端点,它应该执行以下操作:
- 异步启动长时间运行的算法
- 启动算法后立即接受返回202(无等待)
这就是端点的样子:
app.MapPut(
"/api/instance/{id}",
(int id, InstanceDto instanceDto, IInstanceRunningService service) =>
{
// Start the execution asynchronously and return ASAP
service.RunInstance(instanceDto);
return TypedResults.Accepted($"/api/instance/{id}");
})
服务中的RunInstance
方法就是这样的:
public async Task RunInstance(InstanceDto instanceDto)
{
// Asynchronously call another API that we are starting the execution of the algorithm
// We do not need to wait for the response, we just want to start the algorithm ASAP (again no await)
_ = this.AnotherApiClient.PutAsync(instanceDto);
// 计算算法 and await the result
var result = await 算法rithm.Run(instanceDto.Parameters);
// Finally call the other API again to notify that the computation finished
await this.AnotherApiClient.PutAsync(instanceDto);
}
我想要实现的操作顺序是:
- 返回202接受
- 通知另一个API计算正在开始(我们不关心这个API调用如何结束,因为我们将在步骤4中发送另一个.
- 计算算法
- 通知另一个API计算已完成
我想不出实现这一点的最好方法.有太多的 Select :
service.RunInstance(instanceDto);
service.RunInstance(instanceDto).Start();
Task.Run(() => service.RunInstance(instanceDto))
- 将RunInstance设置为异步委托并执行
delegate.BeginInvoke()
- 创建
Thread
或使用ThreadPool
- 也许用更多的rectc方法实现不同的服务,