如何使用调试器处理任务中的异常? [英] How to handle exceptions in Tasks with debugger?

查看:127
本文介绍了如何使用调试器处理任务中的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I studied this article on MSDN, as well as some questions/answers on SO regarding this topic, but cannot figure why below code does not work (in a sample console app).

根据MSDN的预期,将引发AggregateException,其中将包含一个 hello 消息的内部异常。相反,此 hello 异常未处理。

AggregateException is expected to be thrown, according to MSDN, which would contain one inner exception with hello message. Instead, this hello exception is unhandled. It happens when inside a debugger.

如果按继续或独立运行,它将按预期运行。有什么方法可以避免在VS中一直按下继续键吗?毕竟,在单个线程编程模型中, Try ... Catch 块中的所有内容都被视为已处理。否则,调试可能是一场噩梦。

If you press continue or run standalone, it works as expected. Is there any way to avoid pressing continue all the time in VS? After all, whatever is within a Try...Catch block is considered handled in a single threaded programming model. Otherwise, debugging could be a nightmare.

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            
    }
  }
}

推荐答案

设置启用我的代码对此有影响。在工具->选项,调试->常规->启用我的代码下。如果您将其打开,并且您的代码无法处理该异常,它将认为该异常未处理。尝试关闭此选项。

The setting "Enable Just My Code" has an effect on this. Under Tools->Options, Debugging->General->enable Just My Code. If you have it turned on, it will consider the exception unhandled if your code doesn't handle it. Try turning this option off.

请参阅:
http://msdn.microsoft.com/zh-cn/library/dd997415.aspx

这篇关于如何使用调试器处理任务中的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆