C# Desktop Application "Encounters an error and has to exit" on first run of the day
It seems I tend to attract strange issues. This time, I have written a C# application, and handled most of the exceptions I can find. The problem is, when I run the installed/bundled version on any PC for the first time in a day (after the PC has been shut down and started after a while) it comes across some error and has to shutdown the application (even though the try-catch block surrounding the Main() does not fire). The application does not throw the same error on subsequent runs.
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// your event handler
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
// your event handler
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
// you try catch block and Application.Run
try
{
#if(!DEBUG)
Application.EnableVisualStyles();
Application.Run(new newTerminal());
#else
Application.EnableVisualStyles();
newTerminal terminal = new newTerminal();
terminal.ShowDialog();
#endif
}
catch (Exception ex)
{
MessageBox.Show("There was an error loa开发者_开发知识库ding the modules. Please restart the application.", "Oops!");
//return;
CreateLogFiles.ErrorLog("Error: " + ex.Message);
throw ex;
}
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show("There was an error loading the modules. Please restart the application.", "Oops!");
Application.Exit();
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
MessageBox.Show("There was an error loading the modules. Please restart the application.", "Oops!");
Application.Exit();
}
}
There's the full code in Main().Any help is appreciated. I'm running out of time, and getting a bit desparate. Thanks in advance!
surrounding the Main you mean something like this?
static void Main()
{
try
{
//code
}
catch (Exception e)
{
//code
}
}
If you do mean something like this, then try add thread exception handlers:
static void Main()
{
// your event handler
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
// your event handler
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
// you try catch block and Application.Run
}
And if this solution doesnt help you, you can always read about application errors in Windows events repository (control panel-> administration -> events).
Try using AppDomain.UnhandledException
event to log the error before app is closed.
精彩评论