在后台任务中调试异常

时间:2020-07-23 20:33:40

标签: c# visual-studio

我有一个引发错误的后台任务(对象引用未设置为对象的实例)。我希望调试器在发生异常时停止,但事实并非如此。我启用了所有“公共语言运行时异常”。我很确定这与使用async / await有关。

以下代码复制了该行为。该程序的输出符合预期: 你好! 错误:xxx

class Program
{
    public static void Main(string[] args)
    {
        new Test().TestMethod();
        Console.WriteLine("Hello!");
        Console.ReadLine();
    }
}

public class Test
{
    public async void TestMethod()
    {
        try
        {
            await Task.Run(() =>
            {
                throw new Exception("xxx"); // Debugger should stop the execution here
            });
        }
        catch (Exception e)
        {
            Console.WriteLine($"Error: {e.Message}");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

仔细检查您的异常设置,当未处理要抛出的特定异常类型时,您可能没有将Visual Studio设置为中断:

enter image description here