c# – 选择性地防止调试器停止第一次机会异常
我知道我可以防止Visual Studio调试器在抛出某些异常时停止(通过Ctrl-Alt-E“异常”对话框).但是,如果要从代码中控制这些,对于某些特定的地方,而不是在全部或者全部的基础上呢?例如:
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对话框中启用了所有异常.调试器将在循环的每次迭代时停止抛出新的OperationCanceledException(“cancelled1”)行.我不想让它发生,因为它是恼人的.但是,我想让它停止在循环之外的最后一次抛出,抛出新的OperationCanceledException(“cancelled2”)(或其他任何地方). 解决方法
这可能不是你正在寻找的,但是我会使用
DebuggerNonUserCode 属性.
为了说明这一点,这是fiddle的修改版本.即使在Ctrl Alt E Exceptions对话框中启用了OperationCanceledException,调试器也不会停止ThrowIfCancellationRequested. 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,但上述方法说明了可以扩展到任何其他异常的概念. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |