Question

I created a C# console application to handle Ctrl-C by subscribing it to Console.CancelKeyPress event. When I executed (debug version) the application, there were 14 threads already created in the process. When I pressed Ctrl-C a new, 15th thread was created and my handler was invoked. I used process explorer from sysinternals to view the state of the process.

I am curious to know the internals on how the Ctrl-C message is delivered to a process and how the additional thread gets created? I guess, even if I do not subscribe to an event, it will still create an additional thread and exit the process. How is the default mechanism for handling Ctrl-C is setup for an application.

I am a .net developer but want to understand on how the windows operating system works under the hood. The above question is only out of curiosity to learn windows operating system.

Was it helpful?

Solution

When Windows needs to notify a console program of an external event, there is no window message loop to send the notification to, so Windows will create a thread in the target process to execute whatever callback function is defined. The default handler for the CTRL+C event just calls ExitProcess, but hooking the CancelKeyPress event calls the Win32 SetConsoleCtrlHandler function with a handler function.

The documentation for the handler function explains how it works:

An application-defined function used with the SetConsoleCtrlHandler function. A console process uses this function to handle control signals received by the process. When the signal is received, the system creates a new thread in the process to execute the function.

Note that the thread that Windows injects into your process has a fairly small stack, so the CLR handler routine actually queues up a Threadpool work item to execute your event handler. This means that the thread injected by Windows and a worker thread could both be created, causing you to see up to 2 additional threads during the processing of the CTRL+C event.

OTHER TIPS

Yes, Windows starts up a thread to call the handler that's registered by SetConsoleCtrlHandler(). Which is called by the Hook() method of a little internal helper class named ControlCHooker. Which is called by the add() accessor of the Cancel.CancelKeyPress event. The Windows callback makes your event handler run.

A good disassembler like Reflector or ILSpy as well as the Reference Source can help you discover these implementation details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top