最佳答案
我在 ASP.NET 应用程序中有一个方法,它需要花费很多时间来完成。根据用户提供的缓存状态和参数,在一个用户请求期间对此方法的调用最多可能发生3次。每个呼叫大约需要1-2秒才能完成。方法本身是对服务的同步调用,不可能重写实现。
因此,对服务的同步调用如下所示:
public OutputModel Calculate(InputModel input)
{
// do some stuff
return Service.LongRunningCall(input);
}
方法的用法是(注意,方法的调用可能不止一次) :
private void MakeRequest()
{
// a lot of other stuff: preparing requests, sending/processing other requests, etc.
var myOutput = Calculate(myInput);
// stuff again
}
I tried to change the implementation from my side to provide simultaneous work of this method, and here is what I came to so far.
public async Task<OutputModel> CalculateAsync(InputModel input)
{
return await Task.Run(() =>
{
return Calculate(input);
});
}
用法(“ do other stuff”代码的一部分与服务调用同时运行) :
private async Task MakeRequest()
{
// do some stuff
var task = CalculateAsync(myInput);
// do other stuff
var myOutput = await task;
// some more stuff
}
我的问题是。我是否使用了正确的方法来加速 ASP.NET 应用程序的执行,或者我是否做了不必要的工作来尝试异步运行同步代码?有人能解释一下为什么第二种方法在 ASP.NET 中不是一个选项吗(如果它真的不是的话) ?此外,如果这种方法适用,如果这是我们目前可能执行的唯一调用,我是否需要异步调用这种方法(我遇到过这种情况,在等待完成时没有其他事情可做) ?
网上大多数关于这个主题的文章都涉及到使用 async-await
方法的代码,这些代码已经提供了 awaitable
方法,但是这不是我的情况。给你是一篇很好的文章,描述了我的情况,它没有描述并行调用的情况,拒绝了打包同步调用的选项,但是在我看来,我的情况正是这样做的机会。
Thanks in advance for help and tips.