I have a problem that may be fairly unique. I have an application that runs on a headless box for long hours when I am not present, but is not critical. I would like to be able to debug this application remotely using Visual Studio. In order to do so, I have code that looks like this:
// Suspend all other threads to prevent loss
// of state while we investigate the issue.
SuspendAllButCurrentThread();
var remoteDebuggerProcess = new Process
{
StartInfo =
{
UseShellExecute = true,
FileName = MsVsMonPath;
}
};
// Exception handling and early return removed here for brevity.
remoteDebuggerProcess.Start();
// Wait for a debugger attach.
while (!Debugger.IsAttached)
{
Thread.Sleep(500);
}
Debugger.Break();
// Once we get here, we've hit continue in the debugger. Restore all of our threads,
// then get rid of the remote debugging tools.
ResumeAllButCurrentThread();
remoteDebuggerProcess.CloseMainWindow();
remoteDebuggerProcess.WaitForExit();
The idea being that this way, I hit an error while I am away, and the application effectively pauses itself and waits for a remote debugger attach, which after the first continue automatically gets the right context thanks to the Debugger.Break
call.
Here is the problem: Implementing SuspendAllButCurrentThread
turns out to be nontrivial. Thread.Suspend
is deprecated, and I can't P/Invoke down to SuspendThread
because there's no one-to-one mapping between managed threads and native threads (since I need to keep the current thread alive). I don't want to install Visual Studio on the machine in question if it can possibly be avoided. How can I make this work?