A project that I work on was analyzed by a commercial analysis tool. It flagged our implementations of ReaderWriterLockSlim as potential sources of memory leaks because we didn’t call the Dispose() method.
I’ve never seen this method called on this lock: either in code I’ve worked on or code examples I learned from. Should Dispose() be called? What if it’s disposed while a thread still needs it? Is this possible?
Here’s a sample of how we currently use it – no Dispose():
Public Class Test
{
private ReaderWriterLockSlim _lookupLock = new ReaderWriterLockSlim();
public IDictionary<int, SomeObject> GetAll()
{
_lookupLock.EnterWriteLock();
try
{
if (X == null || X.Count == 0)
{
Do Something...;
}
}
finally
{
_lookupLock.ExitWriteLock();
}
return Something...;
}
}
It does need to be disposed.
Mostly a
ReaderWriterLockSlimis used to protect a static resource, so will be a static instance that doesn’t need to be disposed.But in your case (one
ReaderWriterLockSlimper instance), you would need to make your classIDisposable, and dispose theReaderWriterLockSlim.Or maybe a better alternative is to use an ordinary lock (i.e. Monitor) to protect instance resources rather than a
ReaderWriterLockSlim. There’s probably not much performance difference, it makes your code simpler, and it avoids you needing to make your class IDisposable.Framework classes like
ConcurrentDictionaryuse ordinary locks.