Search code examples
c#multithreadingdisposewaithandleresource-leak

Do I need to call Close() on a ManualResetEvent?


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.


Solution

  • In general, if an object implements IDisposable it is doing so for a reason and you should call Dispose (or Close, as the case may be). In the example you site, the ManualResetEvent is wrapped inside a using statement, which will "automatically" handle calling Dispose. In this case, Close is synonymous with Dispose (which is true in most IDisposable implementations that provide a Close method).

    The code from the example:

    using (var mre = new ManualResetEvent(false))
    {
       ...
    }
    

    expands to

    var mre = new ManualResetEvent(false);
    try
    {
       ...
    }
    finally
    {
       ((IDispoable)mre).Dispose();
    }