我在加载事件中创建了一个线程,如下所示:
Thread checkAlert = null;
bool isStop = false;
private void frmMain_Load(object sender, EventArgs e)
{
checkAlert = new Thread(CheckAlert);
checkAlert.Start();
}
void CheckAlert()
{
while (!isStop)
{
Thread.Sleep(60000);
//do work here
}
}
有什么方法可以在 sleep 期间恢复 checkAlert 线程吗?( Thread.Sleep(60000);
)
我尝试使用 Thread.Interrupt()
但它流出一个 ThreadInterruptedException
,我应该如何处理这个异常?或者有什么方法可以恢复线程?
编辑:
我需要在“休眠”结束之前唤醒线程,因为当用户想退出程序时,程序要等一段时间才能真正退出(checkAlert还在运行)有没有什么办法改善这种情况?
最佳答案
根据您的评论,您似乎需要重新设计 CheckAlert
的工作方式,以便它根本不使用 Sleep。你应该做的是使用 Timer
相反。
System.Timers.Timer timer = null;
public FrmMain()
{
InitializeComponent();
timer = new System.Timers.Timer(60000);
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
//If you want OnTimedEvent to happen on the UI thread instead of a ThreadPool thread, uncomment the following line.
//timer.SynchronizingObject = this;
if(this.components == null)
this.components = new System.ComponentModel.Container();
//This makes it so when the form is disposed the timer will be disposed with it.
this.componets.Add(timer);
}
private void frmMain_Load(object sender, EventArgs e)
{
timer.Start();
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
//It is good practice not to do complicated logic in a event handler
// if we move the logic to its own method it is much easier to test (you are writing unit tests, right? ;) )
CheckAlert();
}
void CheckAlert()
{
//do work here
}
private void frmMain_Close(object sender, EventArgs e)
{
timer.Stop();
}
关于c# - 如何唤醒休眠线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20923049/