#if (DEBUG) VS System.Diagnostics.Debugger.IsAttached

前端 未结 6 849
没有蜡笔的小新
没有蜡笔的小新 2020-12-24 11:52

What is different between using #if (DEBUG) and System.Diagnostics.Debugger.IsAttached in visual studio? Are there cases of the DEBUG

相关标签:
6条回答
  • 2020-12-24 11:59

    It has nothing in common. You can debug the Release build. And you can run the Debug build without a debugger, press Ctrl+F5.

    0 讨论(0)
  • 2020-12-24 12:02

    #if DEBUG ensures the code is not included in the assembly at all in release builds. Also, code included by #if DEBUG runs all the time in a debug build - not just when running under a debugger.

    Debugger.IsAttached means the code is included for both debug and release builds. And a debugger can be attached to release builds too.

    It's common to use both together. #if DEBUG is usually used for things like logging, or to reduce exception handling in internal test builds. Debugger.IsAttached tends to just be used to decide whether to swallow exceptions or show them to a programmer - more of a programmer aid than anything else.

    0 讨论(0)
  • 2020-12-24 12:12

    #if (DEBUG) is a preprocessor directive that allows you to conditionally compile code.

    System.Diagnostics.Debugger.IsAttached provides a runtime value that indicates whether a debugger is attached to the process.

    0 讨论(0)
  • 2020-12-24 12:12

    Conditional attributes are another related option to the ones listed above. Good answers related to this topic on this question.

    Need .NET code to execute only when in debug configuration

    0 讨论(0)
  • 2020-12-24 12:21
            private void ConfigureOAuthTokenConsumption(IAppBuilder app)
            {
    #if DEBUG
                AuthenticateViaAppOwnIdentity(app);
    #else
    AuthenticateViaAzureAD(app);
    #endif    
            }
    

    With this code, just try to change the build from debug to release and vice-versa. The running/excluded code will show changed in VS automatically as black and grayed out respectively

    0 讨论(0)
  • 2020-12-24 12:22

    #if DEBUG is a compile-time check, meaning the code it surrounds will only be included in the output assembly if the DEBUG preprocessor symbol is defined. Debugger.IsAttached is a runtime check, so the debugging code still gets included in the assembly, but only executes if a debugger is attached to the process.

    0 讨论(0)
提交回复
热议问题