views:

122

answers:

2

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?

A: 

If you want to do that, don't put your thread to sleep. Take a look at this SO question. Also, this blog entry seems promising.

If you want to GOOGLE more information on it, you might want to seach for "thread signaling" in .NET or something like that.

Pablo Santa Cruz
+8  A: 

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

Adam Sills
It may be better to use an 'AutoResetEvent' in this case, so that questions like 'what happens if T2 signals right after the WaitOne?' do not need to be answered...
jerryjvl
Agreed. AutoResetEvent is probably simpler.
Adam Sills