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

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

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

如果按“继续”或“独立运行”,则按预期工作。 有没有办法避免在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 } } } 

我有什么明显的遗失吗?

设置“启用我的代码”会对此产生影响。 在工具 – >选项,调试 – >常规 – >下启用我的代码。 如果你打开它,如果你的代码没有处理它,它会认为exception未处理。 尝试关闭此选项。

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

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

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