有选择地阻止调试器在第一次机会异常时停止

avo*_*avo 13 .net c# visual-studio task-parallel-library visual-studio-debugging

我知道我可以阻止Visual Studio调试器在抛出某些异常时停止(通过Ctrl-Alt-E"Exceptions"对话框).但是,如果想要从代码中控制这一点,对某些特定的地方而不是全部或全部基础呢?例如:

try
{
    SomeMethod(token);
}
catch (OperationCancelledException)
{
    return false;
}

// ...

void SomeMethod(CancellationToken token)
{
    // ...

    // I don't want the debugger to stop on the following line
    #pragma ignore(OperationCancelledException, true)
    token.ThrowIfCancellationRequested();
    #pragma ignore(OperationCancelledException, false)
} 
Run Code Online (Sandbox Code Playgroud)

我使用假设#pragma ignore来说明我的意思,但这样的事情确实存在吗?

更新以解决"不清楚你在问什么"关闭投票.在调试器中尝试以下代码:https://dotnetfiddle.net/npMk6r.确保在Ctrl-Alt-E对话框中启用了所有异常.调试器将throw new OperationCanceledException("cancelled1")在循环的每次迭代时停止在线上.我不希望这发生,因为它很烦人.然而,我确实希望它在循环外的最后一次投掷中停止throw new OperationCanceledException("cancelled2")(或者在其他地方,就此而言).

nos*_*tio 6

这可能不是你想要的,但我会使用DebuggerNonUserCode属性.

为了说明这一点,这里是你的小提琴的修改版本.ThrowIfCancellationRequested即使OperationCanceledExceptionCtrl+ Alt+ EExceptions对话框中启用,调试器也不会停止.

using System;
using System.Diagnostics;
using System.Threading;

namespace TestApp
{
    static class Ext
    {
        [System.Diagnostics.DebuggerNonUserCode()]
        public static bool TryThrowIfCancellationRequested(
            this CancellationToken token)
        {
            try
            {
                // debugger won't stop here, because of DebuggerNonUserCode attr
                token.ThrowIfCancellationRequested();
                return true;
            }
            catch (OperationCanceledException)
            {
                return false;
            }
        }
    }

    public class Program
    {
        static bool SomeMethod(CancellationToken token)
        {
            System.Threading.Thread.Sleep(1000);
            return token.TryThrowIfCancellationRequested();
        }

        public static void Main()
        {
            var cts = new CancellationTokenSource(1000);

            for (var i = 0; i < 10; i++)
            {
                if (!SomeMethod(cts.Token))
                    break;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以使用CancellationToken.IsCancellationRequested而不是ThrowIfCancellationRequested在这种特定情况下,但上述方法说明了可以扩展到任何其他异常的概念.