I understand that there are a few ways to exit an application, such as Application.Exit(), Application.ExitThread(), Environment.Exit(), etc.
I have an external "commons" library, and I'm trying to create a generic FailIf method that logs the failure to the logs, does this and that and this and that, then finally exits the application... here's a short version of it.
public static void FailIf(Boolean fail, String message, Int32 exitCode = 1)
{
if (String.IsNullOrEmpty(message))
throw new ArgumentNullException("message");
if (fail)
{
//Do whatever I need to do
//Currently Environment.Exit(exitCode)
Environment.Exit(exitCode);
}
}
I have read that using Environment.Exit isn't the best way to handle things when it comes to WinForm apps, and also when working with WPF apps and Silverlight there are different ways to exit... My question is really:
What do I put to exit gracefully to cover all application types?
Read this about the difference between using Environment and Application :
Application.Exit Vs Environment.Exit
There's an example of what you want to do in the bottom of that page:
if (System.Windows.Forms.Application.MessageLoop)
{
// Use this since we are a WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Use this since we are a console app
System.Environment.Exit(1);
}
If it's just an abort, use Environment.Exit()
. If it's something very critical (that can't handle any sort of cleanup), use Environment.FailFast()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With