Home Dashboard Directory Help

ReaderWriterLockSlim does not implement IDisposable properly by Richard Deeming


 as Won't Fix Help for as Won't Fix

Sign in
to vote
Type: Bug
ID: 531334
Opened: 2/5/2010 11:07:50 AM
Access Restriction: Public
User(s) can reproduce this bug


According to the documentation on MSDN [1], "... a Dispose method should be callable multiple times without throwing an exception."

The IDisposable implementation on ReaderWriterLockSlim does not follow this advice - calling Dispose twice results in an ObjectDisposedException.

[1] http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx
Sign in to post a comment.
Posted by Microsoft on 2/8/2010 at 4:06 PM
Thank you for reporting this issue. You are correct that this type does not correctly implement the IDisposable pattern as recommended on MSDN. Unfortunately this does not meet the current bar for fixing this bug in CLR 4, since this type has behaved the same way since it was introduced. However, we will consider fixing this in a future release.

Thanks again,
Eric Eilebrecht
Posted by Microsoft on 2/7/2010 at 8:23 PM
Thank you for reporting the issue.
We were able to reproduce the issue you are seeing. We are routing this issue to the appropriate group within the Visual Studio Product Team for triage and resolution. These specialized experts will follow-up with your issue.
Posted by Microsoft on 2/6/2010 at 7:02 PM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(http://support.microsoft.com)
Posted by Richard Deeming on 2/5/2010 at 11:10 AM
The mistake can be seen quite clearly in the private Dispose(bool) method:

private void Dispose(bool disposing)
    if (disposing)
        if (this.fDisposed)
            throw new ObjectDisposedException(null);

Also, either the class should be sealed or the Dispose(bool) method should be protected and virtual. I suspect that the class should be sealed, as there are no virtual members and no obvious reason to inherit from it.
Sign in to post a workaround.
Posted by Richard Deeming on 2/5/2010 at 11:17 AM
Every time this class is used, you must add a check to ensure that Dispose is only called once:

sealed class Test : IDisposable
    private ReaderWriterLockSlim _guard = new ReaderWriterLockSlim();
    public void Dispose()
        var guard = Interlocked.Exchange(ref _guard, null);
        if (null != guard) guard.Dispose();