簡體   English   中英

異步方法是在調用還是在等待時拋出異常?

[英]Do async methods throw exceptions on call or on await?

當我調用異步方法並返回任務時,是否會立即拋出或等待我等待任務?

換句話說,這段代碼會起作用嗎? 或者我還必須在try-block中包裝方法調用嗎?

Task task = ThisMethodWillThrow();

try
{
    await task;
}
catch (Exception e)
{
    Console.WriteLine("oops");
}

兩者都有可能。 如果該方法實際上是async (即在聲明中使用C# async關鍵字),那么C#編譯器會以一種總是可靠地拋出await的方式將其包裝起來,但重要的是要注意這不是編寫一個可以await的方法的唯一方法,所以:如果你不控制被調用的方法( ThisMethodWillThrow )並且不能依賴於實現的知識,那么try包含初始值會更好調用,以及await

作為一個立即拋出而不是await的方法示例:

Task ThisMethodWillThrow() { // note that this is **not** "async", but is awaitable
    if (thingsAreBad) throw new SomeException();
    return SomeInnerMethod();
}
async Task SomeInnerMethod() { ... }

可能很容易想到“好吧,只是讓所有等待的方法async ,避免這種情況” - 如:

async Task ThisMethodWillThrowToo() { // note that this is "async"
    if (thingsAreBad) throw new SomeException();
    await SomeInnerMethod();
}

但是:在某些情況下,異步機制在“經常同步,有時是異步”的情況下是一個非常可測量的性能開銷 - 因此,性能關鍵等待代碼(例如IO /網絡代碼)中的常見優化是主動避免除非我們知道我們實際上屬於異步路徑,否則async機制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM