Sunday, March 30, 2014

How to stop Thread.Wait

Thead.Wait can't be stop easily, you need to use an alternative solution, by using
ManualResetEvent

ManualResetEvent mre=new ManualResetEvent(false);
//......
var signalled=mre.WaitOne(TimeSpan.FromSeconds(8));
if(signalled)
{
    //cancel the event
}
elsewhere (before the 8 seconds is up):
mre.Set(); //unfreezes paused Thread and causes signalled==true
and allow the unblocked thread to terminate gracefully. Thread.Abort is evil and should be avoided.
Once  mre.Set(), mre.WaitOne(TimeSpan.FromSeconds(8)); mre always return a signal, you need to "unset" the ManualResetEvent by
mre.Reset()

Source

No comments:

Post a Comment