The class AutoResetEvent is used in threading to make one thread wait for a signal, till a specified time.The program execution will continue, if any of the above said situation occurs.ie either on the timeout or on signal arrival.The signal here means calling a method on AutoResetEvent class.
The above said is theory.Lets see how to use this class in practical scenarios.
1: AutoResetEvent autoEvent = new AutoResetEvent(false);
2: bool _canContinue = autoEvent.WaitOne(4000);
3: if (_canContinue)
4: {
5: LogMsg(string.Format("Somebody interupted.So resume"),ConsoleColor.Yellow);
6: }
7: else
8: {
9: LogMsg(string.Format("Nobody interupted.So exit"), ConsoleColor.Yellow);
10: }
After the line WaitOne the thread wait for 4000 seconds or till a signal occurs.If the signal comes the return value will be true.Else false.So if we write the above line in a loop we can continue or exit the loop based on the request.Below is the code to signal or interrupt the thread.
autoEvent.Set();
It is obvious that the autoEvent should have visibility outside the method as well in order to invoke the method.
Practical scenario
You need to write a scheduler which processes queue of objects in a separate thread.The objects to the queue are expected to arrive in a bulk manner.ie the scheduling will happen continuously for a short span of time and rest of the time it will be idle.So once the thread is started and completed one cycle of processing queue, you cannot exit the thread.Rather you need to wait for some time say 4 secs for more items into the queue.But if any object comes to the queue before or with in that 4 secs you need to process those.Else exit the thread after 4 secs.
This scenario has happened in our project and our lead architect came with AutoSetEvent solution.Uploaded a sample which process a list of string in this way.
Another useful classes in threading
ManualResetEvent ,WaitHandle
For better understanding see the Threading sample available in your VisualStudio installation folder. It is located in Language Samples\Threading.It explains threading using the producer-consumers problem.
No comments:
Post a Comment