我研究了this article on MSDN ,以及有关此主题的一些问题/答案,但无法弄清楚为什么下面的代码不起作用(在示例控制台应用程序中)。
根据 MSDN 的说法,预计会抛出 AggregateException,这将包含一个带有 hello
消息的内部异常。相反,未处理此 hello
异常。它发生在调试器中。
如果您按继续或独立运行,它会按预期工作。有没有办法避免在VS中一直按继续?毕竟,Try...Catch
block 中的任何内容在单线程编程模型中都被视为已处理。否则,调试可能是一场噩梦。
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
}
}
}
我在这里明显遗漏了什么吗?
最佳答案
设置“仅启用我的代码”对此有影响。在 Tools->Options,Debugging->General->enable Just My Code 下。如果您打开它,如果您的 代码没有处理它,它将认为异常未处理。尝试关闭此选项。
关于c# - 如何使用调试器处理任务中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14990998/