如何唤醒沉睡的线程? [英] How to Wake up a sleeping thread?

查看:36
本文介绍了如何唤醒沉睡的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 load 事件中创建了一个线程,如下所示:

I made a thread at load event like below:

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);)

Is there any way to resume the checkAlert thread during it's sleep period?( Thread.Sleep(60000);)

我尝试使用 Thread.Interrupt() 但它流了一个 ThreadInterruptedException,我应该如何处理这个异常?或者有什么办法可以恢复线程?

I tried using Thread.Interrupt() but it flows a ThreadInterruptedException, how should I handle this exception? or is there any way to resume the thread?

我需要在sleep"结束前唤醒线程,因为当用户想要退出程序时,程序将不得不等待一段时间才能真正退出(checkAlert仍在运行)有什么办法吗?改善这个案例?

I need to wake up the thread before the "sleep" end because when the user wants to quit the program, the program will have to wait for some time before it really quits ( checkAlert is still running) Is there any way to improve this case?

推荐答案

根据您的评论,您需要重新设计 CheckAlert 的工作方式,使其根本不使用 Sleep 的.您应该做的是使用 定时器代替.

Based on your comments what it looks like is you need to re-design how CheckAlert works so it does not use Sleep's at all. What you should be doing is using a Timer instead.

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();
}

这篇关于如何唤醒沉睡的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆