Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running code when C# debugger detaches from process

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.

like image 1000
Geert van Horrik Avatar asked Feb 16 '14 15:02

Geert van Horrik


People also ask

Why my C program is not running in VS code?

Go to the menu Code > Preferences > Settings. In the User tab on the left panel, expand the Extensions section. Find and select Run Code Configuration. Find and check the box Run in Terminal.

How do I get C to work on Vscode?

We need to click on the extension button that displays a sidebar for downloading and installing the C/C++ extension in the visual studio code. In the sidebar, type C Extension. In this image, click on the Install button to install the C/C++ extension.

Can C run in Vscode?

C/C++ support for Visual Studio Code is provided by a Microsoft C/C++ extension to enable cross-platform C and C++ development on Windows, Linux, and macOS.


1 Answers

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)

like image 105
Iain Ballard Avatar answered Nov 26 '22 05:11

Iain Ballard