2012-10-23 57 views
2

我相信我doinig有什么问题,但是当我尝试这个新的线程任务异常处理的例子时,我不断收到用户代码未处理的异常。代码的重点是展示如何捕捉任务错误的例子。C# - 任务异常未被捕获

链接:Task Exception Example

static void Main(string[] args) 
     { 
      var task1 = Task.Factory.StartNew(() => 
      { 
       throw new MyCustomException("I'm bad, but not too bad!"); 
      }); 

      try 
      { 
       task1.Wait(); 
      } 
      catch (AggregateException ae) 
      { 
       // Assume we know what's going on with this particular exception. 
       // Rethrow anything else. AggregateException.Handle provides 
       // another way to express this. See later example. 
       foreach (var e in ae.InnerExceptions) 
       { 
        if (e is MyCustomException) 
        { 
         Console.WriteLine(e.Message); 
        } 
        else 
        { 
         throw; 
        } 
       } 

      } 
     } 

最有可能的用户错误只是不知道什么(使用Visual Studio 2012);

+3

在大黄色框中滚动到“注释”。 :) – mayhewr

回答

14

从你所引用的页面:

注意

启用“仅我的代码”时,Visual Studio在某些情况下会 突破上抛出异常并显示一条线错误 消息表示“异常未由用户代码处理”。这个错误是 良性。您可以按F5继续并查看这些示例中演示的异常处理 行为。为了防止Visual Studio打破第一个错误,只需取消选中工具,选项,调试,常规下的“仅我的 代码”复选框。