Any way to sleep at a breakpoint in C # / Visual Studio?

Is there a way to delay the execution of the current thread for a certain period of time when hitting a breakpoint in C # / Visual Studio? After sleep, execution should continue.

I know that in VS there is a function β€œWhen hit”, which allows you to execute arbitrary code when you reach a breakpoint (primarily for printing information to the console), but it is very limited; it does not allow you to put Thread.Sleep or any labor-intensive operations (e.g. for loops). Lambda delegates / functions are also not allowed.

I am working with Visual Studio 2012.

+6
source share
1 answer

I have my own solution, which requires a one-time recompilation. I am sure that it can be translated into C # if necessary.

Define this structure:

 struct THREAD_DATA { int ms; DWORD id; THREAD_DATA(DWORD _id, int _ms) : id(_id), ms(_ms) {}; }; 

and these two functions:

 DWORD WINAPI PauseThread(LPVOID p) { THREAD_DATA* ptd = (THREAD_DATA*)p; HANDLE target = OpenThread(THREAD_SUSPEND_RESUME, FALSE, ptd->id); SuspendThread(target); Sleep(ptd->ms); ResumeThread(target); delete p; return 0; } void PauseCurrentThread(int ms) { THREAD_DATA* ptd = new THREAD_DATA(GetCurrentThreadId(), ms); HANDLE h = CreateThread(NULL, 0, &PauseThread, (LPVOID)ptd, 0, 0); } 

When you are at a breakpoint, use the Immediate window to launch: PauseCurrentThread(5000) or regardless of your delay in milliseconds.

If you want to do this in several projects without tools, I could probably develop a Visual Studio extension to do this automatically.

0
source

All Articles