在方法范围内禁用调试器中断

Disable debugger break in a method scope

BackgroundWorker 实例中,我通过测试 e.Error 属性 处理从 DoWork 方法抛出到 RunWorkerCompleted 方法中的 Exception

private string Test()
{
    // For the example, always throw an Exception
    throw new Exception("Unknown error");
}

private void DoWork(object sender, DoWorkEventArgs e)
{
    // Will always throw an Exception
    e.Result = Test();
}

private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null)
    {
        // Exception is managed here
    }
    else
    {
        // Nevers appends in this example
    }
}

我的问题是调试器总是中断程序,因为 "non-catched" 异常(不是 "non-managed")被 Test 抛出。

如何在 DoWork 范围内禁用调试器?

在调试期间,我不想在 DoWork 范围内中断程序,因为我知道异常将在 RunWorkerCompleted.

中进行管理

如果您将属性 [DebuggerNonUserCode] 添加到事件处理程序,它将不再被调试器的默认设置拾取。

public class Program
{

    public static void Main(string[] args)
    {
        BackgroundWorker bw = new BackgroundWorker();
        bw.DoWork += Bw_DoWork;
        bw.RunWorkerCompleted += Bw_RunWorkerCompleted;
        bw.RunWorkerAsync();
        Console.ReadLine();
    }

    [DebuggerNonUserCode] //Comment this line to see the difference.
    private static void Bw_DoWork(object sender, DoWorkEventArgs e)
    {
        throw new InvalidOperationException(); 
    }

    private static void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Debugger.Break();
    }
}

请注意,您需要在调试器设置中启用 "Just My Code"(默认情况下启用)。