在调试器下运行时更改程序流程
题
有什么方法可以检测调试器是否在内存中运行?
这是表单加载伪代码。
if debugger.IsRunning then
Application.exit
end if
编辑: 原标题是“检测内存调试器”
解决方案
尝试使用以下
if ( System.Diagnostics.Debugger.IsAttached ) {
...
}
其他提示
在使用它关闭调试器中运行的应用程序之前要记住两件事:
- 我使用调试器从商业 .NET 应用程序中提取崩溃跟踪并将其发送到公司,随后修复了该问题,并感谢您使这一切变得简单和
- 该检查可以是 琐碎地 打败了。
现在,为了更有用,以下是如何使用此检测来保持 函数评估 如果您出于性能原因缓存了延迟评估的属性,则可以在调试器中更改程序状态。
private object _calculatedProperty;
public object SomeCalculatedProperty
{
get
{
if (_calculatedProperty == null)
{
object property = /*calculate property*/;
if (System.Diagnostics.Debugger.IsAttached)
return property;
_calculatedProperty = property;
}
return _calculatedProperty;
}
}
我有时也使用此变体来确保我的调试器单步执行不会跳过评估:
private object _calculatedProperty;
public object SomeCalculatedProperty
{
get
{
bool debuggerAttached = System.Diagnostics.Debugger.IsAttached;
if (_calculatedProperty == null || debuggerAttached)
{
object property = /*calculate property*/;
if (debuggerAttached)
return property;
_calculatedProperty = property;
}
return _calculatedProperty;
}
}
不隶属于 StackOverflow