How to awaken a sleeping thread?

I made a thread on a load event, as shown 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 a way to resume checkAlert flow during this sleep period? ( Thread.Sleep(60000);)

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


Edited by:

I need to wake the thread until the end of the "sleep", because when the user wants to exit the program, the program will have to wait a while before it really leaves (checkAlert still works). Is there any way to improve this case?

+4
source share
4 answers

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

, , , .

checkAlert = new Thread(CheckAlert);
checkAlert.IsBackground = true;
checkAlert.Start();
+3

, , : - .

(isStop) ( UI Event ) .

AutoResetEvent stop = new AutoResetEvent(false);
AutoResetEvent check = new AutoResetEvent(false);

private void CheckAlert() {
    WaitHandle[] handles = new WaitHandle[] { stop, check };
    for (;;) {
        switch (AutoResetEvent.WaitAny(handles)) {
            case 0:
                return;
            case 1:
                // do work
                break;
        }
    }
}

check.Set() "do work" , stop.Set() , .

stop.Set() , Join(), .

. , - . , , , ​​ , :

AutoResetEvent stop = new AutoResetEvent(false);

void CheckAlert() {
    var time = new TimeSpan(0, 1, 0); // one minute
    while (!stop.WaitOne(time)) {
        // do work
    }
}

private Thread checkThread;

private void frmMain_Load(object sender, EventArgs e) {
    checkThread = new Thread(CheckAlert);
    checkThread.Start();
}

private void frmMain_Close(object sender, EventArgs e) {
    stop.Set();  // signal thread to stop
    checkThread.Join();  // wait for thread to terminate
}
+1

, :

https://msdn.microsoft.com/en-us/library/tttdef8x%28v=vs.100%29.aspx

( , Thread.Interrupt - ... , ):

public class HVCSensor : HVCDevice, IDisposable
{
    private Thread myThread;
    private const int execute_timeout = ((10 + 10 + 6 + 3 + 15 + 15 + 1 + 1 + 15 + 10) * 1000);
    private bool disposed = false;
    private bool paused = false;

    public delegate void HVCResultsHandler(HVC_RESULT res);
    public event HVCResultsHandler HVCResultsArrived;

    private void OnHVCResultsArrived(HVC_RESULT res)
    {
        if (HVCResultsArrived != null) {
            HVCResultsArrived(res);
        }
    }

    public HVCSensor() {
        myThread = new Thread(new ThreadStart(this.execute));

    }

    private void execute(){
        while (!disposed) {
            if (!paused && this.IsConnected)
            {
                HVC_RESULT outRes;
                byte status;
                try
                {

                    this.ExecuteEx(execute_timeout, activeDetections, imageAcquire, out outRes, out status);
                    OnHVCResultsArrived(outRes);
                }
                catch (Exception ex) {

                }

            }
            else {
                try
                {
                    Thread.Sleep(1000);
                }
                catch (ThreadInterruptedException e)
                {

                }
            }


        }
    }

    public HVC_EXECUTION_IMAGE imageAcquire
    {
        get;
        set;
    }
    public HVC_EXECUTION_FLAG activeDetections
    {
        get;
        set;
    }

    public void startDetection() {
        if(myThread.ThreadState==ThreadState.Unstarted)
            myThread.Start();
    }

    public void pauseDetection() {
        paused = true;
    }

    public void resumeDetection() {

        paused = false;
        if (myThread.ThreadState == ThreadState.WaitSleepJoin)
            myThread.Interrupt();

    }

    // Implement IDisposable. 
    // Do not make this method virtual. 
    // A derived class should not be able to override this method. 
    public void Dispose()
    {
        disposed = true;
        myThread.Interrupt();


    }

}
+1

All Articles