我已經實現了我的自定義ThreadManager
,它在我的測試過程中一直以完美的方式工作。當用戶想要關閉應用程序時,關閉會暫停,直到所有線程退出,或者他們選擇結束應用程序而不等待(30秒後)。FormClosing事件中的Application.DoEvents
我需要澄清的是如果在FormClosing
事件中使用Application.DoEvents()
可能會有危險。我應該使用它還是找到另一種等待線程退出的方式?
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;
}
的何苦用戶?他們知道發生了什麼事嗎?在我的大多數應用程序中,我只是立即退出應用程序,因爲沒有理由不這樣做。在奇怪的情況下,當我必須確定某個文件已關閉或數據庫連接已經釋放時,我只需將應用程序最小化,然後等待一段定時器以「線程關閉」消息或BeginInvokes()或其他任何內容進入。 – 2012-07-25 11:33:19
的確,有一個數據庫連接必須被釋放,並且還有必須返回的WebBrowser或WatiN調用,因此不推薦使用該應用程序。最小化與顯示等待表單並無太大區別。 – iCantSeeSharp 2012-07-25 11:55:28