如何在不等待的情況下安全地呼叫 C# 中的非同步方法 - How to safely call an async method in C# without await

語言: CN / TW / HK

問題:

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 請求呼叫中等待將在響應請求之前等待任務完成,從而無緣無故地增加響應時間。


解決方案:

參考一: https://stackoom.com/question/138DM
參考二: How to safely call an async method in C# without await
「其他文章」