Threading and ManualResetEvent vs Thread.Sleep

Found this really interesting post on StackOverflow that clarified the performance difference between using events and the more obvious but less efficient Thread.Sleep().

We have a real-time messaging app that we wanted to wait on calling back the client if a message was not queued up for delivery (to avoid unnecessary callbacks if messages were not being sent). The original implementation used a while loop with a call to thread.sleep, but after a few hundred users were utilizing the system we would get some strange behaviors and performance issues. Not all the time, but some of the time.

Currently the code is being revised to utilize the ManualResetEvent class. The event driven model (not related in this case to .net events) for having the thread wait on certain actions would be the better way to do this and obviously if I knew anything about thread programming in .NET at the time I would have seen this right away, but we live and learn.

In the case of a ManualResetEvent you utilize the Set and Reset calls in combination with the WaitOne() call to indicate that where threads will wait and when they can continue. The Reset event signals the start of the wait for whatever activity needs to be waited on and the Set event indicates when threads can proceed.

Leave a Reply

Your email address will not be published. Required fields are marked *