如何使用调试器处理任务中的异常?

时间:2013-02-20 22:16:55

标签: c# .net vb.net exception task-parallel-library

我研究了this article on MSDN,以及有关此主题的SO的一些问题/答案,但无法理解为什么下面的代码不起作用(在示例控制台应用程序中)。

根据MSDN,预计会抛出AggregateException,它将包含一个带有hello消息的内部异常。相反,此hello异常未处理。它发生在调试器内部。

如果您按继续或独立运行,它将按预期工作。有没有办法避免在VS中一直按下继续?毕竟,Try...Catch块中的任何内容都被视为在单线程编程模型中处理。否则,调试可能是一场噩梦。

VB.NET

Sub Main()
  Try
    Task.Factory.StartNew(AddressOf TaskThatThrowsException).Wait()
  Catch ex As AggregateException
    Console.WriteLine(ex.ToString) 'does not get here until you hit Continue
  End Try
End Sub

Private Sub TaskThatThrowsException()
  Throw New Exception("hello") 'exception was unhandled
End Sub

C#

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      try {
        Task.Factory.StartNew(TaskThatThrowsException).Wait();
      }
      catch (AggregateException ex) {
        Console.WriteLine(ex.ToString()); //never gets here                
      }
    }

    static void TaskThatThrowsException() {
      throw new Exception("hello"); //exception was unhandled            
    }
  }
}

这里有什么显而易见的东西吗?

2 个答案:

答案 0 :(得分:2)

这很可能是因为您误解了Visual Studio对话框的内容。

例外是“用户未处理”,因为没有捕获它的用户代码(原始Exception),它被TPL捕获。因此,如果您让调试器继续运行,或者如果您在没有调试器的情况下运行应用程序,您将看到您期望的行为。

答案 1 :(得分:2)

设置“启用我的代码”会对此产生影响。在工具 - >选项,调试 - >常规 - >下启用Just My Code。如果您已打开它,如果您的代码无法处理,则会认为异常未处理。尝试关闭此选项。

请参阅: http://msdn.microsoft.com/en-us/library/dd997415.aspx