FormClosing事件中的Application.DoEvents

时间:2012-07-25 10:43:46

标签: c# multithreading doevents formclosing

我已经实现了我的自定义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;
}

1 个答案:

答案 0 :(得分:3)

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

致电possible drawbacks

加分主题 Application.DoEvents Method