Exit sleep blocking program? How is this implemented?

In a single-threaded console application, people often use Thread.Sleep as a lazy way to pause the application for some time.

This question raised interesting points about NOT using this approach: Why Thread.Sleep is so harmful

However, not knowing that โ€œSleepโ€ blocks the current thread, I donโ€™t understand how it works - for example, does it maximize the processor core in a narrow cycle or does it really stop the thread?

More importantly for me, how does a console application respond to various exit scenarios of applications (CTRL-C, kill, window close button) when they get into the middle of sleep? Will he blindly continue execution until the power of the OS kills him, or will he behave well?

+5
source share
2 answers

This is more of an OS question than a C # /. NET related question, but I will try to answer briefly.

Thread.Sleep will not block your CPU; instead, it will call the appropriate mechanism in the underlying OS to suspend your thread. In windows, this function is described here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686298(v=vs.85).aspx

Using this normal system call, your thread cannot be carried forward before the timeout expires. Then the forced destruction of the thread (or the entire process) is required.

When you press ctrl + c in cmd.exe, the console will create a new thread in each process connected to handle the event (described here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682541(v = vs.85) .aspx ), because of this, your program as a whole will continue to "behave" when you press ctrl + c, but your sleeping thread itself will be killed prematurely.

+5
source

This is the source code for the Thread.Sleep method:

 [System.Security.SecuritySafeCritical] // auto-generated public static void Sleep(int millisecondsTimeout) { SleepInternal(millisecondsTimeout); // Ensure we don't return to app code when the pause is underway if(AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); } 

As we can see, this method calls the Thread.SleepInternal method. In the commentary on this, we can read that this method pauses the current thread for timeouts in milliseconds. Then we can read that if timeout == 0, this method forces the thread to abandon the rest of its time-lapse, and if the time-out is Timeout.Infinite, then the time-out will not occur. I recommend that you read the multithreading and application life cycle (in this case, especially paused).

References:

+2
source

All Articles