I have a class MyClass
. This class have a field: public ReaderWriterLockSlim rw;
(public for an easier example code). Many threads can read data from MyClass
using rw.EnterReadLock
etc.
Also I have implemented IDisposable
interface:
private void Dispose (bool pDisposing)
{
{
if (pDisposing) // release managed resources
{
if (rw != null)
{
rwLockSlim.Dispose ();
rwLockSlim = null;
}
}
//--- release unmanaged resources
// some code...
isDisposed = true; // ...
}
}
Like you see, problem is when one thread is using MyClass
when second thread call Dispose
on myClass object. I cannot dispose ReaderWriterLockSlim because it will crash my application. So should I just remove that lines which releases managed resources? Anyway that ReaderWriterLockSlim will be collected by GC in near future, right? (but is this class resource expensive?).
Maybe I should add some lock(syncObject) in Dispose metod or something?
EDIT: also I deal with AllocHGlobal, so I need to wait, until all threads will stop reading/writing to myClass
.
Different point of view:
public MyClass : IDisposable
{
public void EnterReadLock (); // calls rwLockSlim.EnterReadLock,
// if object is disposed throws Exception
public void ExitReadLock (); // same as above
public void Dispose (); // wait until all threads exit from locks,
// frees unamanged resources, mark class as disposed
}