Eric Eilebrecht's blog

When should you call RegisteredWaitHandle.Unregister?

The managed ThreadPool provides a way to asynchronously wait for WaitHandles, via ThreadPool.RegisterWaitForSingleObject. This method returns a new instance of RegisteredWaitHandle, which has a single method: Unregister.  It's obvious from the name that this will cancel a pending wait operation.  What's not obvious is that even after a registered wait has completed, you should still call Unregister.

The reason is that RegisteredWaitHandle holds a reference to your WaitHandle, and holds a refcount on the underlying SafeHandle.  If you don't call Unregister, then RegisteredWaitHandle will have to run its finalizer sometime later, before it can release the WaitHandle.  Calling Unregister prevents the finalizer from running (which helps perf), and may get your handle closed faster.

RegisteredWaitHandle really, really should implement IDisposable.

Published Thursday, March 13, 2008 5:05 PM by ericeil
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required
Submit

About ericeil

I have been working for Microsoft since 1997. I started as a test developer in the Windows team, then moved on to develop backend storage services for Hotmail (now Windows Live). I am currently a developer on the Common Language Runtime team, where I work on threading.

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker