1

我已经实现了我的习惯ThreadManager,在我的测试过程中它一直在完美地工作。当用户想要关闭应用程序时,关闭会暂停,直到所有线程退出或他们选择不等待就结束应用程序(经过 30 秒后)。

我需要澄清的是,如果使用Application.DoEvents()可能会很危险FormClosing。我应该使用它还是找到另一种等待线程退出的方法?

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    // save settings before exit
    Properties.Settings.Default.Save();

    // Update program about intention
    Program.ApplicationClosing = true;

    try
    {
        // Inform user with friendly message
        ShowModalWaitForm("Application is closing.");

        // Keep the timestamp in order to keep track of how much time has passed since form closing started
        DateTime startTime = DateTime.Now;

        // Wait for all threads to die before continuing or ask user to close by force after 30 seconds have passed
        // In case user prefers to wait the timer is refreshed
        int threadsAlive;
        do
        {
            if (_threadManager.TryCountAliveThreads(out threadsAlive) && threadsAlive > 0)
            {
                Application.DoEvents();
                Thread.Sleep(50);
            }

            TimeSpan timePassed = DateTime.Now - startTime;
            if (timePassed.Seconds > 30)
            {
                if (ShouldNotWaitThreadsToExit())
                {
                    break; // Continue with form closing
                }
                else
                {
                    startTime = DateTime.Now; // Wait more for threads to exit
                }
            }
        } while (threadsAlive > 0);
    }
    catch (Exception ex)
    {
        _logger.ErrorException("MainForm_FormClosing", ex);
    }
    finally
    { 
        HideWaitForm(); 
    }
}


private bool ShouldNotWaitThreadsToExit()
{
    return MessageBox.Show(@"Press ""OK"" to close or ""Cancel"" to wait.", "Application not responding ", MessageBoxButtons.OKCancel) == DialogResult;
}
4

1 回答 1

3

我建议将您的等待条件放在另一个线程中。从 OnFormClosing 方法显示一个模式对话框。在此对话框中启动工作线程,例如使用BackGroundWorker 类并在等待完成时关闭此对话框。

奖金主题 调用Application.DoEvents 方法的可能缺点

于 2012-07-25T10:59:12.630 回答