在调试器下运行时更改程序流程

16

有没有办法检测内存中是否运行了调试器?

这里是Form Load伪代码。

if debugger.IsRunning then
Application.exit
end if

编辑: 原标题为“检测内存中的调试器”


1
大多数调试器可以在运行时附加到进程上。在这种情况下,启动时检查调试器并不能提供太多帮助。 - Michał Piaskowski
2个回答

33

尝试以下方法

if ( System.Diagnostics.Debugger.IsAttached ) {
  ...
}

5
使用此方法关闭在调试器中运行的应用程序前,请记住以下两点:
  1. 我曾使用调试器从商业.NET应用程序中获取崩溃跟踪并将其发送给公司,随后得到了感谢,并使其易于修复。
  2. 该检查可以轻松地被击败。
现在,为了更有用,以下是如何使用此检测来防止 func eval 在调试器中更改您的程序状态(如果您具有缓存懒惰计算属性以提高性能)。
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;
    }
}

这是一个不错的想法,但在调试器下运行时会改变程序的流程,因此您不能再调试发布版本中使用的代码。在我看来,在大多数情况下最好提供非缓存变量的属性(在# if DEBUG内,以便在发布版中不构建),您可以在调试器中使用它来检查值,保留“真实”属性以相同方式在调试和发布版本中工作。 - Jason Williams
@Jason:是的和不是。在这种情况下,用于评估属性的所有方法都是纯的(无论何时调用都没有副作用),因此我实际上是确保从应用程序的角度来看,属性也是如此。 - Sam Harwell
你认为这种方法是否有效,如果你想创建一个仅在 Visual Studio 的调试模式下工作的库?我想创建一个可以在 Visual Studio 中自由测试但不能包含在发布模式下构建的应用程序中的库。 - Jose Manuel Ojeda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接