我研究了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
}
}
}
有什么明显的,我在这里失踪?
设置调试器停止对所有异常。它停在哪里?它应该停在'TaskThatThrowsException'和'Wait'中。 – usr 2013-02-20 22:25:28
@usr:即使现在它停止在抛出新的异常(“你好”)线,检查所有投掷并没有使它变得更好。我希望它不止于此,而是处理Console.WriteLine。否则,调试可能是一场噩梦。 – Neolisk 2013-02-21 02:31:45
任务异常不会出现在StartNew中,只出现在.Wait()中。 Dim myTask = Task.Factory.StartNew(...)试试MyTask.Wait()Catch ... – adrianm 2013-02-21 13:21:31