Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

waking up one thread from another

I am using .NET (C#).

if I have 2 threads running T1 and T2 and T1 is like this:

while (true) 
{
  dosomething(); //this is a very fast operation
  sleep(5 seconds);
}

at the same time T2 is doing something completely different however from time to time it needs to give T1 a kick such that it wakes up from the sleep even though the sleep time is not up. How do I do this?

like image 669
freddy smith Avatar asked Dec 17 '22 07:12

freddy smith


1 Answers

Use a WaitHandle, like ManualResetEvent (or AutoResetEvent).

In your class, declare a ManualResetEvent:

private ManualResetEvent myEvent = new ManualResetEvent(false);

Thread1:

while(true) {
    doSomething();
    myEvent.WaitOne(5000);
    myEvent.Reset();
}

Thread2:

myEvent.Set();

Thread1 will wait for 5 seconds or until the ManualResetEvent is Set, whichever comes first.

EDIT: added AutoResetEvent above

like image 164
Adam Sills Avatar answered Dec 19 '22 19:12

Adam Sills