I would like to be able to trap CTRL+C in a C# console application so that I can carry out some cleanups before exiting. What is the best way of doing this?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
See MSDN:
Console.CancelKeyPress Event
Article with code samples:
Ctrl-C and the .NET console application
Console.TreatControlCAsInput = true;
has worked for me.I'd like to add to Jonas' answer. Spinning on a
bool
will cause 100% CPU utilization, and waste a bunch of energy doing a lot of nothing while waiting for CTRL+C.The better solution is to use a
ManualResetEvent
to actually "wait" for the CTRL+C:This question is very similar to:
Capture console exit C#
Here is how I solved this problem, and dealt with the user hitting the X as well as Ctrl-C. Notice the use of ManualResetEvents. These will cause the main thread to sleep which frees the CPU to process other threads while waiting for either exit, or cleanup. NOTE: It is necessary to set the TerminationCompletedEvent at the end of main. Failure to do so causes unnecessary latency in termination due to the OS timing out while killing the application.
The Console.CancelKeyPress event is used for this. This is how it's used:
When the user presses Ctrl + C the code in the delegate is run and the program exits. This allows you to perform cleanup by calling necessairy methods. Note that no code after the delegate is executed.
There are other situations where this won't cut it. For example, if the program is currently performing important calculations that can't be immediately stopped. In that case, the correct strategy might be to tell the program to exit after the calculation is complete. The following code gives an example of how this can be implemented:
The difference between this code and the first example is that
e.Cancel
is set to true, which means the execution continues after the delegate. If run, the program waits for the user to press Ctrl + C. When that happens thekeepRunning
variable changes value which causes the while loop to exit. This is a way to make the program exit gracefully.Here is a complete working example. paste into empty C# console project: