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

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

我研究了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 下。如果您打开它,如果您的 代码没有处理它,它将认为异常未处理。尝试关闭此选项。

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

关于c# - 如何使用调试器处理任务中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14990998/

相关文章:

c# - 将 JSON 反序列化为对象时出现问题

c# - 使用 System.Uri 删除多余的斜线

c# - GetMethod 返回 null

javascript - 在填写联系表单后,如何让用户返回到他们原来的页面?

vb.net - 如何将 "System.Drawing.Image"带到 DIB

c# - 直接下载文件到内存

c# - 在 C# 中制作泛型表达式生成方法

c# - 如何在 C# 中对列表进行排序

c# - RestSharp 不反序列化 JSON 对象列表,始终为 Null

c# - csharp 中的 foreach 语句错误中都需要类型和标识符