Running code when C# debugger detaches from process

c#, debugging, windows-phone, windows-runtime

Solution

Probably the simplest way is to have a thread watching the value. Something like:

public class DebugEventArgs : EventArgs {
    public bool Attached { get; set; }
}
class Watcher {
    public event EventHandler<DebugEventArgs>  DebuggerChanged;

    public Watcher() {
        new Thread(() => {
            while (true) {
                var last = System.Diagnostics.Debugger.IsAttached;
                while (last == System.Diagnostics.Debugger.IsAttached) {
                    Thread.Sleep(250);
                }
                OnDebuggerChanged();
            }
        }){IsBackground = true}.Start();
    }

    protected void OnDebuggerChanged() {
       var handler = DebuggerChanged;
       if (handler != null) handler(this, new DebugEventArgs { Attached = System.Diagnostics.Debugger.IsAttached });
    }
}

(written but not compiled)

Problem

I am currently trying to run some code when the debugger detaches from a process. It is easy to find out if a debugger is attached: ``` System.Diagnostics.Debugger.IsAttached; ``` My question is if there is a way (preferable one that works for .NET, Windows Phone, WinRT) to get an event when the debugger gets detached (mostly when the application is killed). Worst case I can find the debugger Process in .NET and subscribe to the Exit event, but that won't work in Windows Phone and WinRT.

Original source