开发者

Generic way to exit a .NET application

开发者 https://www.devze.com 2023-02-05 15:15 出处:网络
I understand that there are a few ways to exit an application, such as Application.Exit(), Application.ExitThread(), Enviro开发者_如何学运维nment.Exit(), etc.

I understand that there are a few ways to exit an application, such as Application.Exit(), Application.ExitThread(), Enviro开发者_如何学运维nment.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().


I would recommend using basic exception handling, so instead of System.Environment.Exit(1) throw new ApplicationException(message) which bubbles up the exception to the main method, in your case something like this:

try{
Application.Run(new MyForm());
}
catch(ApplicationException){
// do custom cleanup/reporting
}

Just make sure you throw the exception from the main thread, else invoke on it before throwing ofcourse

0

精彩评论

暂无评论...
验证码 换一张
取 消