Awakening one thread from another

I am using .NET (C #).

if I have 2 threads working with T1 and T2, and T1 looks like this:

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

at the same time, T2 does something completely different, but from time to time he needs to give T1 a blow so that he wakes up from sleep, even if the sleep time is not up. How to do it?

+4
source share
2 answers

Use WaitHandle, such as ManualResetEvent (or AutoResetEvent ).

In your class, declare ManualResetEvent:

 private ManualResetEvent myEvent = new ManualResetEvent(false); 

Thread1:

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

Thread 2:

 myEvent.Set(); 

Thread1 will wait 5 seconds or until the ManualResetEvent parameter is set, whichever comes first.

EDIT : Added AutoResetEvent above

+12
source

If you want to do this, do not put the thread to sleep. Take a look at this SO question. Also, this blog post seems promising.

If you want GOOGLE to contain additional information about it, you might want to ask for "streaming signaling" in .NET or something like that.

0
source

Source: https://habr.com/ru/post/1285881/


All Articles