c# - 如何唤醒休眠线程?

标签 c# multithreading

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

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/

相关文章:

c# - 检查 SQL Server 数据库表中是否存在表或列

ios - 如何在 swift 中处理递归函数中的不同线程?

Java Spring Boot - 用于在后台运行的异步数据库操作的 CommandLineRunner

c# - 使用任务的意外线程中止异常。为什么?

c# - WPF PropertyChanged 代码错误 : cannot implement 'System. ComponentModel.INotifyPropertyChanged

c# - 如何使用 microsoft.interop.word 从 word 文件中读取项目符号列表?

c# - ASP.net - Azure AD - Request.IsAuthenticated 总是 false 为什么?下一个

c# - 如何在文本框中使用 double?

c++ - pthread_mutex_lock 阻塞但 __lock = 0

c++ - 将参数传递给Boost线程函数