簡體   English   中英

C#:在沒有 [await] 的情況下調用 [async] 方法不會捕獲其拋出的異常?

[英]C#: calling [async] method without [await] will not catch its thrown exception?

我有這個代碼片段:

class Program
{
    public static async Task ProcessAsync(string s)
    {
        Console.WriteLine("call function");
        if (s == null)
        {
            Console.WriteLine("throw");
            throw new ArgumentNullException("s");
        }
        Console.WriteLine("print");
        await Task.Run(() => Console.WriteLine(s));
        Console.WriteLine("end");
    }
    public static void Main(string[] args)
    {
        try
        {
            ProcessAsync(null);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

它運行並打印:

call function
throw

好的,拋出異常,但是主函數的 try/catch 無法捕獲異常,如果我刪除 try/catch,main 也不會報告未處理的異常。 這很奇怪,我用谷歌搜索,它說 [await] 中有陷阱,但沒有解釋如何以及為什么。

所以我的問題是,為什么這里沒有捕獲異常,使用 await 的陷阱是什么?

非常感謝。

async方法中,任何異常都會被運行時捕獲並放置在返回的Task 如果您的代碼忽略async方法返回的Task ,則不會觀察到這些異常。 大多數任務應該在某個時候await以觀察它們的結果(包括異常)。

最簡單的解決方案是使您的Main異步:

public static async Task Main(string[] args)
{
  try
  {
    await ProcessAsync(null);
  }
  catch(Exception e)
  {
    Console.WriteLine(e.Message);
  }
}

暫無
暫無

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

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