我知道我可以阻止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)
}
我使用假设#pragma ignore
来说明我的意思,但确实存在这样的事情吗?
更新以解决问题"不清楚您的问题"关闭投票。在调试器中尝试此代码:https://dotnetfiddle.net/npMk6r。确保在Ctrl-Alt-E对话框中启用了所有异常。每次循环迭代时,调试器将在throw new OperationCanceledException("cancelled1")
行停止。我不希望这件事发生,因为它很烦人。然而,我确实希望它停止在循环外的最后一次投掷throw new OperationCanceledException("cancelled2")
(或其他任何地方,就此而言)。
答案 0 :(得分:6)
这可能不是您正在寻找的,但我会使用DebuggerNonUserCode
属性。
为了说明这一点,这里是fiddle的修改版本。即使在{kbd> Ctrl + Alt + E 例外中启用了ThrowIfCancellationRequested
,调试器也不会停在OperationCanceledException
上对话框。
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;
}
}
}
}
当然,在这种特殊情况下,您可以使用CancellationToken.IsCancellationRequested
代替ThrowIfCancellationRequested
,但上述方法说明了可以扩展到任何其他异常的概念。
答案 1 :(得分:1)
您尝试以下方式:
当&#34; Just My Code&#34;启用后,Visual Studio在某些情况下会在抛出异常的行上中断,并显示一条错误消息,指出&#34;异常不由用户代码处理。&#34;这个错误是良性的。您可以按F5继续它,并查看以下示例中演示的异常处理行为。 要防止Visual Studio在第一个错误中出现问题,只需取消选中&#34; Just My Code&#34; “工具”,“选项”,“调试”,“常规”下的复选框。
来自here
希望这会有所帮助
答案 2 :(得分:-1)
你想要什么可以表达为
try
{ // #pragma ignore(OperationCancelledException, true)
token.ThrowIfCancellationRequested();
}
catch (OperationCancelledException op)
{ // #pragma ignore(OperationCancelledException, false)
// ignore
}
但这被认为是一种不好的做法。应该以某种方式处理例外情况。至少出于一些调试原因。