---
title: "Capture console exit C#"  
description: "Capture console exit C#"  
author: "marcel ethan"  
published: 2013-12-12  
updated: 2013-12-12  
canonical: https://www.mindstick.com/forum/1771/capture-console-exit-c-sharp  
category: "c#"  
tags: ["c#"]  
reading_time: 2 minutes  

---

# Capture console exit C#

I have a [console application](https://www.mindstick.com/forum/160510/how-to-fetch-data-from-the-database-in-the-dot-net-console-application-using-c-sharp) that contains quite a lot of [threads](https://www.mindstick.com/blog/11678/threads-in-java). There are threads that monitor certain conditions and terminate the [program](https://www.mindstick.com/blog/12337/scaling-up-your-mentorship-program) if they are true. This termination can happen at any time.

I need an [event](https://www.mindstick.com/articles/167719/marquee-hire-benefits-of-event-lighting-hire-london) that can be triggered when the program is closing so that I can cleanup all of the other threads and [close](https://yourviews.mindstick.com/story/1687/rubbing-hands-close-up-benefits) all file handles and [connections](https://yourviews.mindstick.com/view/87707/baba-siddique-murder-news-his-connections-with-underworld) properly. I'm not sure if there is one [already](https://yourviews.mindstick.com/view/88453/the-hidden-ways-ai-is-already-controlling-your-daily-life) built into the .NET [framework](https://www.mindstick.com/forum/34615/software-framework-vs-library), so I'm asking before I write my own.

I was wondering if there was an event along the lines of:

MyConsoleProgram.OnExit += CleanupBeforeExit;

\
Please Help.

## Replies

### Reply by Pravesh Singh

Hi Marcel,\
\

This will allow you to do cleanup code in your [console](https://www.mindstick.com/blog/210/the-console-class), e.g. when it is abruptly closed or due to a shutdown...

```
[DllImport("Kernel32")]private static extern bool SetConsoleCtrlHandler(EventHandler
handler, bool add);private delegate bool EventHandler(CtrlType sig);static EventHandler _handler;enum CtrlType{  CTRL_C_EVENT = 0,  CTRL_BREAK_EVENT =
1,  CTRL_CLOSE_EVENT =
2,  CTRL_LOGOFF_EVENT =
5,  CTRL_SHUTDOWN_EVENT
= 6}private static bool Handler(CtrlType sig){  switch (sig)  {      case
CtrlType.CTRL_C_EVENT:      case
CtrlType.CTRL_LOGOFF_EVENT:      case
CtrlType.CTRL_SHUTDOWN_EVENT:      case
CtrlType.CTRL_CLOSE_EVENT:      default:  }}static void Main(string[] args){  // Some biolerplate
to react to close window event  _handler += new
EventHandler(Handler); 
SetConsoleCtrlHandler(_handler, true);  ...}
```


---

Original Source: https://www.mindstick.com/forum/1771/capture-console-exit-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
