I have a small form that creates two background worker threads which listen for messages from two separate server processes. When the user attempts to close the form, I handle the OnFormClosing event (or they can click an 'Exit menu item) which calls CancelAsync() on both threads. The form then waits until the IsBusy property for both threads is "FALSE" before calling Environment.Exit(0).
Here is the catch: From this Form, the user is able to launch a separate application. This is done using Process.Start when a specific button is clicked. If the user has created a new process via the Form, and then closes the Form, instead of exiting gracefully it crashes and I get one of those windows error messages. Application.Exit doesn't work because it won't close the form for some reason unbeknown to me. I'm certain that both threads are finished executing because I handle the RunWorkerCompleted event for both threads. Here is a shell of the core code:
private void startProcess_buttonClick(sender, e)
{
Process.Start(<process args>);
}
protected override OnFormClosing()
{
e.Cancel = true;
if (!thread1.IsBusy && !thread2.IsBusy)
Environment.Exit(0);
stopThreads();
}
private void stopThreads()
{
if (thread1.IsBusy)
thread1.CancelAsync();
if (thread2.IsBusy)
thread2.CancelAsync();
}
private void thread1_RunWorkerCompleted(sender, e)
{
if (!thread2.IsBusy)
Environment.Exit(0);
}
private void thread2_RunWorkerCompleted(sender, e)
{
if (!thread1.IsBusy)
Environment.Exit(0);
}
Any ideas as to what would be causing the crash on Environment.Exit?