.NET thread synchronization

I plan to use the Auto reset Event Handle to communicate between threads.

EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.AutoReset); 

My producer thread code looks below

 produceSomething(); handle.Set(); 

In the consumer stream, I have to load data every minute or when the producer is called the Set method

 try { while(true) { handle.WaitOne(60000, false); doSomething(); // Downloads data from Internet. // Takes lot of time to complete it. } } catch(ThreadAbortException) { cleanup(); } 

My question is, doSomething consumer thread and producer call set function work, what will the state of the reset object of the <object be? >

My requirement, as soon as the calling method calls the call, I need to download the latest data from the Internet. If the doSomething function doSomething started when Producer calls the dialing method, I have to abort it and call again.

+6
c #
source share
2 answers

The auto-reset event is like a shutter that closes after passing through the first thread. If you install it while one or more threads are waiting, then one thread wakes up, then the reset event, the other threads continue to wait.

If you set when the threads are not waiting, the first thread that calls handle.WaitOne will not wait, but this will cause the event to get reset, and then continue to work.

from http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx

Call Set Alarms AutoResetEvent to release the pending stream. AutoResetEvent remains a signal until one waiting thread is released, and then automatically returns to a non-signaling state. If the threads do not wait, the state remains undefined.

If a thread calls WaitOne and AutoResetEvent is in a signal state, the thread is not blocked. AutoResetEvent immediately releases the thread and returns to the no-signal state.

+2
source share

The problem with the auto-reset event in your scenario is that the “setup” does not support the order.

That is, setting the auto-reset event allows one thread to be injected, if you set it before any thread “swallows” your event, then this “set” will be lost. You can expect that two threads will be able to input and consume everything that you created, but in reality only one thread can do it.

In your case, if you are running faster than you consume, the auto-reset event may be skipped. Imagine this case.

  • The manufacturer creates one item.
  • The user consumes the item (discards the event and starts loading from inet)
  • The manufacturer produces the second item.
  • The manufacturer produces the third item.
  • The product stops.
  • The user consumes the second element (loads the event and starts the download again).
  • The user will not use the third item because the auto-secret event was reset.
+1
source share

All Articles