Solved

How to cleanly exit a program?

Posted on 2010-09-11
9
315 Views
Last Modified: 2013-12-17
I have a C# program running under .NET 2.0, that does some checking for files, etc.  If the files are missing, I want to halt the program.  Right now I'm throwing an exception, which I would like to avoid if possible (that was the only way I could kill the program).  

I have tried Application.Exit(), but the program just continues on as if the statement wasn't executed, which I know it was.

Any ideas?
0
Comment
Question by:rmmarsh
  • 4
  • 3
  • 2
9 Comments
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 33653491
Show us some code...especially the main loop of your app!

What event/method is the code running from?

Is it using a thread?

Details, details, details!...  =)
0
 

Author Comment

by:rmmarsh
ID: 33653585
Oops... sorry...

//  check for internet connection  
            ss.Text = "checking internet connection";
            ss.Refresh();
            fTrace("I - checking internet connection");
            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                fTrace("E - no internet connection");
                DialogResult dlgResult = DialogResult.None;
                dlgResult = MessageBox.Show("No internet connection; do you wish to work offline?", "Prager, Software", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlgResult == DialogResult.Yes)
                    workOfflineToolStripMenuItem.Checked = true;
                else
                    throw new System.ArgumentException("no internet connection");
            }

            FileInfo fi;
            if (dbPath.IndexOf(':') == dbPath.LastIndexOf(':'))
                fi = new FileInfo(dbPath);
            else
            {
                int i = dbPath.IndexOf(':');
                string filePath = @"\\" + dbPath.Substring(0, i) + @"\";
                //filePath += dbPath.Substring(i + 1, dbPath.Length - i - 1);
                filePath += dbPath.Substring(i + 3, dbPath.Length - i - 3);
                fi = new FileInfo(filePath);
            }

            if (!fi.Exists)  //  if the database is missing, stop...
            {
                fTrace("E - database is missing");
                MessageBox.Show("The database is missing and the program can not continue. \nNotify support@pragersoftware.com for help", "Prager, Software", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                throw new System.ArgumentException("database is missing");
            }

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 33653601
...okay...and WHERE is that code running from?  It looks like a WinForms app...what event is that in?  WHO is catching the exception and what are you doing with it?
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

Author Comment

by:rmmarsh
ID: 33653631
OK... the code is in the mainForm.cs file... it's the first bit of code that get's executed before the user is presented with the main window.  There are two event handlers to catch the thrown exception (see code below).

Then this code is executed to handle the exception:

        internal static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {

            Exception ex = (Exception)e.ExceptionObject;

            Application.Exit();
        }



// Add the event handler for handling UI thread exceptions to the event.
                Application.ThreadException += new ThreadExceptionEventHandler(mainForm.Form1_UIThreadException);

                // Add the event handler for handling non-UI thread exceptions to the event. 
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(mainForm.CurrentDomain_UnhandledException);

Open in new window

0
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 100 total points
ID: 33653710
So in program.cs, you start your app with?

            Application.Run(new mainForm());

and you are executing this code in the Load() or Shown() event of mainForm?

You should just be able to Close() the form instead of throwing an exception...

Change these:

    throw new System.ArgumentException("no internet connection");
    throw new System.ArgumentException("database is missing");

To:

    this.Close();
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33653758
Have you any other forms running? Try closing all your forms including the one running before you issue Application.Exit
0
 
LVL 65

Accepted Solution

by:
rockiroads earned 400 total points
ID: 33653771
someone struggling with closing, but has examples of closing http://www.experts-exchange.com/Programming/Languages/.NET/Q_26462772.html
0
 

Author Closing Comment

by:rmmarsh
ID: 33653841
Thanks everybody... the following line of code solved my problem...

System.Diagnostics.Process.GetCurrentProcess().Kill()
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 33653858
That's like using a sledge hammer to put in a finishing nail...

There is a proper, less severe way to close your program but we need more information to establish a better understanding of the setup and flow in your app...thus all my questions.

Good luck!...  =)
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question