Tuesday, October 13, 2009

How to detect whether application is being run in Debug mode?

I don’t mean the question “How to detect whether application is built in Debug configuration”. It is achieved with the help of conditional compilation.
I mean – how to detect whether your application is being debugged from Visual Studio or other external debugger (no matter in which configuration it is built: Debug, Release or something else).
The answer is simple:


The property returns true if any debugger is attached to the application’s process.

We use this approach in DataObjects.Net v4 internal logging subsystem: if DataObjects.Net v4 is built in Debug configuration, logging is always enabled and by default log messages are written into DebugLog (it redirects them to Debug.WriteLine method). In Release configuration we check the presence of attached debugger. If debugger is attached, we follow the same logic as in Debug configuration; otherwise all messages are written in NullLog (/dev/null). So no performance overhead is produced.

Sample code that demonstrates the approach:

    protected override ILog GetLog(string name)
      return new DebugLog(name);
      return Debugger.IsAttached ? new DebugLog(name) : new NullLog(name);

No comments:

Post a Comment