Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Wake up a sleeping thread?

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
   }
}

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

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?


Edited:

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?

like image 288
User2012384 Avatar asked Feb 15 '23 05:02

User2012384


2 Answers

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();
}
like image 96
Scott Chamberlain Avatar answered Feb 26 '23 20:02

Scott Chamberlain


If you want the thread to exit automatically when your program quits, simply make it a background thread.

checkAlert = new Thread(CheckAlert);
checkAlert.IsBackground = true;
checkAlert.Start();
like image 41
Kendall Frey Avatar answered Feb 26 '23 20:02

Kendall Frey