Solved

How to cleanly exit a program?

Posted on 2010-09-11
9
318 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

 

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

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

735 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