Changing the program flow when running under a debugger

拜拜、爱过 提交于 2019-11-30 17:35:30

Try the following

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

Two things to keep in mind before using this to close an application running in the debugger:

  1. I've used a debugger to pull a crash trace from a commercial .NET application and send it to the company where it was subsequently fixed with a thank you for making it easy and
  2. That check can be trivially defeated.

Now, to be of more use, here's how to use this detection to keep func eval in the debugger from changing your program state if you have a cache a lazily evaluated property for performance reasons.

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;
    }
}

I've also used this variant at times to ensure my debugger step-through doesn't skip the evaluation:

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!