gpt4 book ai didi

c# - FormClosing事件中的Application.DoEvents

转载 作者:行者123 更新时间:2023-12-03 13:21:16 31 4
gpt4 key购买 nike

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

最佳答案

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

调用possible drawbacks的奖励主题 Application.DoEvents Method

关于c# - FormClosing事件中的Application.DoEvents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11647973/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com