RE: Auto-restarting Forms Applications
- From: William Sullivan <WilliamSullivan@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 30 Jun 2006 08:10:02 -0700
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.
"TJO" wrote:
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() );
}
}
- References:
- Auto-restarting Forms Applications
- From: TJO
- Auto-restarting Forms Applications
- Prev by Date: Re: accessing to windows register
- Next by Date: Re: How to force SplitContainer's contents to change 'on-the-fly' during resizing
- Previous by thread: Re: Auto-restarting Forms Applications
- Next by thread: ErrorProviders and How can I encapsulate business logic in typed datasets???
- Index(es):
Relevant Pages
|