首页 / C# / c# – 如何唤醒睡眠线程?
c# – 如何唤醒睡眠线程?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 如何唤醒睡眠线程?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1650字,纯文字阅读大概需要3分钟。
内容图文
我在load事件中创建了一个线程,如下所示:
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
}
}
有没有办法在休眠期间恢复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# – 如何唤醒睡眠线程?全部内容,希望文章能够帮你解决c# – 如何唤醒睡眠线程?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。