How can I fire off a function when it detects the console closing when using Environment.Exit(0)?
How can I fire off a function when it detects the console closing when
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The simplest way of doing this is probably to handle the
AppDomain.ProcessExitevent, which is raised when the application’s parent process exits.For example:
But calling
Environment.Exitmay not be the best solution to your original problem. In general, the only time it is necessary to use this method is when there might be other foreground threads running. And in that case, it’s worth investigating ways of gracefully terminating those other threads without resorting to draconian measures that kill the entire process.Environment.Exit, despite the somewhat pleasant-sounding name, is a pretty brutal measure. It’s not quite as bad as clicking “End Task” in the Windows Task Manager (and note that if you do that, theProcessExitevent will not be raised, meaning that the above suggestion will not work), but it’s probably not the solution you really want, either.