المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Catch Asynchronous Exception?



C# Programming
03-12-2010, 03:40 AM
My program has a main message loop as follows:
ContextMenu trayMenu = new ContextMenu();
//Add “Launch” options to menu here
trayIcon = new NotifyIcon();
trayIcon.Visible = true;
trayIcon.MouseDoubleClick += new MouseEventHandler(trayIcon_MouseDoubleClick);
//MouseEventHandler calls MainForm.Invoke(...) to show the new form on main thread
while (true)
{
try {
MainForm = new Form();
MainForm.WindowState = FormWindowState.Minimized;
MainForm.ShowInTaskbar = false;

Application.Run(MainForm);
}
catch (Exception)
{
//”call home” logic here to report the exception
continue;
}

break; //Run() exited normally
}
When my forms (made on main thread via trayIcon_MouseDoubleClick) throw an exception (on the main thread) they are caught with the above method and the program keeps on running just fine and I can lauch another form via the trayIcon;

My issue is that my forms that are being made call other functions asyncronously, and if those functions throw exceptions they are not caught and my program crashes.

I’m starting the asyncronous functions via System.Threading.ThreadPool.QueueUserWorkItem() incase it makes a difference.

My question is, how can I catch these exceptions?

Thank you all for your knowldege and advice!