I’ve been reading up on .NET Threading and was working on some code that uses a ManualResetEvent. I have found lots of code samples on the internet. However, when reading the documentation for WaitHandle, I saw the following:
WaitHandle implements the Dispose
pattern. See Implementing Finalize and
Dispose to Clean Up Unmanaged
Resources.
None of the samples seem to call .Close() on the ManualResetEvent objects they create, even the nice Recursion and Concurrency article from the pfxteam blog (Edit – this has a using block I has missed). Is this just example oversight, or not needed? I am curious because a WaitHandle “encapsulates operating system–specific objects,” so there could easily be a resource leak.
In general, if an object implements
IDisposableit is doing so for a reason and you should callDispose(orClose, as the case may be). In the example you site, the ManualResetEvent is wrapped inside ausingstatement, which will “automatically” handle callingDispose. In this case,Closeis synonymous withDispose(which is true in mostIDisposableimplementations that provide aClosemethod).The code from the example:
expands to