I have an async
method which returns no data:
(我有一个不返回任何数据的async
方法:)
public async Task MyAsyncMethod()
{
// do some stuff async, don't return any data
}
I'm calling this from another method which returns some data:
(我从另一个返回一些数据的方法中调用此方法:)
public string GetStringData()
{
MyAsyncMethod(); // this generates a warning and swallows exceptions
return "hello world";
}
Calling MyAsyncMethod()
without awaiting it causes a " Because this call is not awaited, the current method continues to run before the call is completed " warning in visual studio.
(在MyAsyncMethod()
调用MyAsyncMethod()
而不等待它会导致“ 因为未等待此调用,因此当前方法将在调用完成之前继续运行 ”警告。)
On the page for that warning it states: (在该警告的页面上,它指出:)
You should consider suppressing the warning only if you're sure that you don't want to wait for the asynchronous call to complete and that the called method won't raise any exceptions .
(仅当您确定不想等待异步调用完成并且被调用的方法不会引发任何异常时 ,才应考虑禁止显示警告。)
I'm sure I don't want to wait for the call to complete;
(我确定我不想等待通话结束。)
I don't need to or have the time to. (我不需要或没有时间。)
But the call might raise exceptions. (但是通话可能会引发异常。)
I've stumbled into this problem a few times and I'm sure it's a common problem which must have a common solution.
(我已经几次遇到这个问题,并且我确定这是一个常见的问题,必须有一个通用的解决方案。)
How do I safely call an async method without awaiting the result?
(如何安全地调用异步方法而不等待结果?)
Update: (更新:)
For people suggesting that I just await the result, this is code that is responding to a web request on our web service (ASP.NET Web API).
(对于建议我只是等待结果的人,这是响应我们Web服务(ASP.NET Web API)上的Web请求的代码。)
Awaiting in a UI context keeps the UI thread free, but awaiting in a web request call will wait for the Task to finish before responding to the request, thereby increasing response times with no reason. (在UI上下文中等待将保持UI线程空闲,但是在Web请求调用中等待将等待Task完成,然后再响应请求,从而无故增加了响应时间。)
ask by George Powell translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…