Capture console exit C
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Capturing console application exit in C# allows you to perform cleanup (closing files, flushing logs, releasing resources) before the process terminates. The primary mechanism is Console.CancelKeyPress for Ctrl+C handling. For other exit scenarios (window close, system shutdown), use the Win32 SetConsoleCtrlHandler API via P/Invoke. AppDomain.CurrentDomain.ProcessExit fires on normal exit but has a strict time limit.
Console.CancelKeyPress (Ctrl+C / Ctrl+Break)
Setting args.Cancel = true prevents the default behavior (immediate termination) and lets your code run cleanup logic before calling Environment.Exit().
AppDomain.ProcessExit (Normal Exit)
ProcessExit fires when the application exits normally (end of Main, Environment.Exit). It does NOT fire on forced kills (taskkill /F, kill -9).
SetConsoleCtrlHandler (All Exit Types)
For comprehensive exit detection including window close and system shutdown, use the Win32 API:
Using CancellationToken (Modern Approach)
This is the recommended pattern for modern .NET applications. CancellationToken propagates through async methods, allowing graceful shutdown of all background tasks.
.NET Generic Host (ASP.NET Core / Worker Services)
The Generic Host handles Ctrl+C, SIGTERM, and process exit automatically, calling StopAsync on all hosted services.
Linux/macOS Signal Handling (.NET 6+)
Common Pitfalls
- ProcessExit time limit: The
ProcessExithandler has approximately 2 seconds to complete. Long cleanup operations get cut off. Move heavy cleanup to beforeMainreturns. args.Cancel = trueonly works for Ctrl+C: SettingCancelinCancelKeyPressprevents termination for Ctrl+C, butCTRL_CLOSE_EVENT(window close) gives you only about 5 seconds regardless.- SetConsoleCtrlHandler is Windows-only: The P/Invoke approach does not work on Linux/macOS. Use
PosixSignalRegistration(.NET 6+) for cross-platform signal handling. Environment.Exit()skips finally blocks: CallingEnvironment.Exit(0)from a handler terminates immediately, skippingfinallyblocks in other threads. UseCancellationTokenfor cooperative shutdown.- SIGKILL / taskkill /F cannot be caught:
kill -9andtaskkill /Fterminate the process immediately with no opportunity for cleanup. Design your application to recover from unclean shutdowns.
Summary
- Use
Console.CancelKeyPressfor Ctrl+C handling withargs.Cancel = trueto prevent immediate exit - Use
AppDomain.CurrentDomain.ProcessExitfor normal exit cleanup (2-second limit) - Use
SetConsoleCtrlHandler(Windows) orPosixSignalRegistration(.NET 6+, cross-platform) for comprehensive signal handling - The modern pattern uses
CancellationTokenfor cooperative async shutdown - .NET Generic Host handles exit signals automatically for hosted services
- No mechanism can catch forced kills (
kill -9,taskkill /F)
Related reading
- Capture Stored Procedure print output in .NET
- Capturing console output from a .NET application C
- Case insensitive string compare in LINQ-to-SQL
- Cast received object to a Listobject or IEnumerableobject
- Casting interfaces for deserialization in Json.NET
- Casting NewType vs. Object as NewType
- Casting TResult in TaskTResult to System.Object
- Catch an exception thrown by an async void method

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.