我正在 ASP.NET 中实现 REST API 端点,它应该执行以下操作:
这就是端点的样子:
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);
// Compute the algorithm and await the result
var result = await Algorithm.Run(instanceDto.Parameters);
// Finally call the other API again to notify that the computation finished
await this.AnotherApiClient.PutAsync(instanceDto);
}
我想要实现的操作顺序是:
我无法找出实现这一目标的最佳方法。有很多选择:
service.RunInstance(instanceDto);
service.RunInstance(instanceDto).Start();
Task.Run(() => service.RunInstance(instanceDto))
delegate.BeginInvoke()
Thread
或使用 ThreadPool