Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Windows Forms / WinForm General / June 2006

Tip: Looking for answers? Try searching our database.

Auto-restarting Forms Applications

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
TJO - 28 Jun 2006 01:17 GMT
I am trying to understand how to restart a windows form application in
the event of an unexpected exception on the main form. I want to have
the program attempt to restart the application 3 times then fail
gracefully.  The problem I am experiencing is this seems to work fine
for the first 2 attempts but the third time the program abruptly stops
at the point of the Exception and never gets to the handler on the
Program.  Please advise, thank you.

    static class Program
    {
        static int restartCount = 3;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        ///[STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault( false );
            Application.ThreadException += new
System.Threading.ThreadExceptionEventHandler(
Application_ThreadException );

            AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );
            Application.SetUnhandledExceptionMode(
UnhandledExceptionMode.CatchException);

            restart();

            //Application.Run( new Form1() );
            Application.Run();

            Console.WriteLine( "Program.Main() error handler" );

        }

        static void Application_ThreadException( object sender,
System.Threading.ThreadExceptionEventArgs e )
        {
            Console.WriteLine( "ThreadException Handled" );
            restart();
        }

        static void CurrentDomain_UnhandledException( object sender ,
UnhandledExceptionEventArgs e )
        {
            Console.WriteLine( "UnhandledException Handled" );
            restart();
        }

        static void restart()
        {
            restartCount--;

            if(restartCount < 0)
                Environment.Exit( 0 );

            if (restartCount > -1)
            {
                Console.WriteLine( "Attempting Restart #{0}" , 3 - restartCount );

                Form1 form = new Form1();
                form.ShowDialog();

            }
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            myFuction();
        }

        private void myFuction()
        {
            object o = null;

            // This will throw exception
            Console.WriteLine( ((Control) o).ToString() );
        }
    }
Pitaridis Aristotelis - 28 Jun 2006 07:08 GMT
I had the same problem and I finally found the Application.Restart( )
method. If you find an other method, please let me know

Aristotelis

> I am trying to understand how to restart a windows form application in
> the event of an unexpected exception on the main form. I want to have
[quoted text clipped - 82 lines]
> }
> }
TJO - 28 Jun 2006 14:37 GMT
I have used this but the underlying inability to properly shutdown and
restart remains.  The error on subsequent attempts after the first few
is not handled.

> I had the same problem and I finally found the Application.Restart( )
> method. If you find an other method, please let me know
[quoted text clipped - 87 lines]
> > }
> > }
Mehdi - 28 Jun 2006 08:43 GMT
> I am trying to understand how to restart a windows form application in
> the event of an unexpected exception on the main form. I want to have
[quoted text clipped - 3 lines]
> at the point of the Exception and never gets to the handler on the
> Program.  Please advise, thank you.

I can't give you a definite answer as to why it works 2 times and fails the
3rd time but this behaviour doesn't surprises me. In your unhandeld
exception handler, you are calling restart() which itslef throws an
exception. If exceptions throws in an unhandled exception handler caused
your unhandled exception handler to be called then you could very easily
end up in an infinite loop (and since unhandled exceptions usually happen
when something goes really wrong, such as the state of your application
being corrupted beyond repair the system having run out of memory, it is
common that code in the unhandled exception handler fails too). So the CLR
must take steps to avoid that.

In addition, if your application threw an unhandled exception, simply
recreating the main form and re-showing it would probably not be a great
solution anyway. In your basic app, you only have an empty main form so
that's ok but in a real world application, you would have hundredrs or
thousands of objects and static data loaded in memory, ressources hold and
so on. Recreating the main form would only add to the confusion and
probably cause even more errors. When something goes really wrong, you
should shut down the process to allow for memory and other resources to be
released and then restart the whole process. You can use Process.Start()
and Application.StartupPath to restart your application. If you want to
monitor the number of times that you have restarted your application, you
could write this information in the registry or in a file in the
application's IsolatedStorage.
TJO - 28 Jun 2006 14:43 GMT
I realize that shutting down is the best thing to do. My goal here is
to try go have the application restart itself until the administrator
can reboot it and thereby try to keep things as seemless as possible.

My actual production application will send text message alerts to the
administrator so that he will know the program crashed.  He will also
be notified when the maximum number of attempted restarts has been
reached.

You have gottem me to think that throwing exceptions within exceptions
may be the issue.  I will continue researching.

If anyone else cares to assist.  The program sample I provided in my
first post does illustrate to problem so you can run it too.

Thanks for everyone input.
Chris Chilvers - 29 Jun 2006 00:55 GMT
>I realize that shutting down is the best thing to do. My goal here is
>to try go have the application restart itself until the administrator
[quoted text clipped - 12 lines]
>
>Thanks for everyone input.

An alternative solution could be to have a monitor app that detects when
the program is not running and reloads it, as if it completely crashes
out with some form of thread death there is no guarantee that it will
ever run an exception handler or finally block.
William Sullivan - 30 Jun 2006 16:10 GMT
If this app needs to be running all the time, you should look into rewriting
it as a service.  Or using a service to perform the operations that must be
running all the time.  Run your code on a worker thread and handle thread
aborts by attempting to restart the thread.  You should do some reading on
multithreading, as it is much easier to gracefully recover from a thread
crashing than your entire program crashing.

> I am trying to understand how to restart a windows form application in
> the event of an unexpected exception on the main form. I want to have
[quoted text clipped - 82 lines]
>         }
>     }

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.