使用Process.Start时,Environment.Exit()会导致我的应用程序崩溃

时间:2010-10-09 22:33:29

标签: c# winforms crash backgroundworker environment

我有一个小表单,它创建了两个后台工作线程,用于侦听来自两个独立服务器进程的消息。当用户尝试关闭表单时,我处理OnFormClosing事件(或者他们可以单击“退出”菜单项),该事件在两个线程上调用CancelAsync()。然后表单等待,直到两个线程的IsBusy属性为“FALSE”,然后再调用Environment.Exit(0)。

以下是捕获:从此表单中,用户可以启动单独的应用程序。单击特定按钮时,使用Process.Start完成此操作。如果用户通过表单创建了一个新进程,然后关闭表单,而不是正常退出它崩溃,我得到其中一个Windows错误消息。 Application.Exit不起作用,因为它不会因为我不知道的某些原因而关闭表单。我确定两个线程都已完成执行,因为我处理了两个线程的RunWorkerCompleted事件。这是核心代码的shell:

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);
}

关于什么会导致Environment.Exit崩溃的想法?

2 个答案:

答案 0 :(得分:3)

尝试

Application.Exit()

因为您正在运行Windows窗体。我自己没有做过测试用例,但我很确定Winforms API对于通过使用内核API的Environment立即终止进程感到非常不满。

我也发现了这个:http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx

答案 1 :(得分:0)

怎么样

protected override OnFormClosing()
{
    e.Cancel = true;

    if (!thread1.IsBusy && !thread2.IsBusy)
       this.Close();

    stopThreads();
}
private void thread1_RunWorkerCompleted(sender, e)
{
       if (!thread2.IsBusy)
          this.Close();
}
private void thread2_RunWorkerCompleted(sender, e)
{
       if (!thread1.IsBusy)
          this.Close();
}