2017-04-20 77 views
3

我試圖捕捉將由Task.Factory.StartNew方法引發的NullReferenceException。我認爲它應該通過task.Wait()方法的'try'語句來捕獲。我也提到Why is this exception not caught?,但不知道。你會分享你的智慧嗎?AggregateException未捕獲Task.Wait()

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Threading; 
using System.Threading.Tasks; 

namespace Csharp_study 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Task my_task = Task.Factory.StartNew(() => { throw null; }); 
      try 
      { 
       my_task.Wait(); 
      } 

      catch (AggregateException exc) 
      { 
       exc.Handle((x) => 
        { 
         Console.WriteLine(exc.InnerException.Message); 
         return true; 
        }); 
      } 

      Console.ReadLine(); 
     } 
    } 
} 

回答

2

此行爲是由於VS的調試器,而不是你的代碼。

如果您處於調試模式並且啓用了只是我的代碼(這是大多數語言的默認設置),關閉它應該有所訣竅。

要禁用「只是我的代碼」功能,請轉到工具>選項>調試>常規,然後取消選中只是我的代碼複選框。

如果您想知道啓用Just My Code功能的功能是什麼,請點擊msdn

啓用僅我的代碼
啓用此功能,調試 顯示器和步驟爲用戶代碼(「我的代碼」)只,忽略系統 代碼和其他的代碼進行了優化,或者沒有調試 符號。

+1

謝謝。事實上,我在3個月前自己找到答案,因爲我在下面的一個發表了評論。但我找不到解決問題的方法。所以我把你的標記爲一個。祝你今天愉快! –

1

如果您想處理任務異常,請檢查它是否有故障。如果沒有故障繼續執行。

static void Main(string[] args) 
     { 
      Task my_task = Task.Factory.StartNew(() => { throw null; }); 

      my_task.ContinueWith(x => 
      { 

       if (my_task.IsFaulted) 
       { 
        Console.WriteLine(my_task.Exception.Message); 

       } 
       else { 
        //Continue with Execution 
       } 
      }); 
     } 

而且return true;在這種情況下無效的,因爲方法沒有返回類型。

+0

你好。感謝您的解決方案。這是有道理的,但有什麼其他方式可以處理異常?像使用傳統的異常處理語句。我還提到[MSDN](https://msdn.microsoft.com/en-us/library/system.aggregateexception(v = vs.110).aspx),但它也可以捕獲Task的異常。等待()。 –

+0

從上面繼續,我也嘗試了你的解決方案,但仍然得到相同的異常說'未處理',並且它看起來代碼沒有處理異常。 –

+0

在處理任務時,如果發生故障並且上面的代碼正常工作,則必須檢查狀態。你有完整的代碼嗎? – Simsons