Friend,
I have a class that contains some data. The data will be accessed from
multiple threads of which 90% are reading and 10% are writing. A private
ReaderWriterLockSlim object is used within the class to facilitate
synchronization.
You're probably aware that ReaderWriterLockSlim implements IDisposable. So
to honor the contract with ReaderWriteLockSlim, it stands to reason that
*my* class must implement IDisposable so that when my class is disposed, so
is the private lock object.
Here's the problem. Various instances of my class are passed around from
place to place throughout the application and it's impossible for me as the
programmer to determine at precisely what point any given instance of the
class will no longer be referenced. I normally wouldn't care (that's what
the Garbage Collector is for) but in this case, I need to know so that
Dispose() can be called on my class.
The best solution I could come up with is to have my class maintain an
internal reference count. Each time the class is passed to some using
entity, AddRef() is called to increment the count and when that using entity
is done referencing my class, Release() is called to decrement the count.
When the count reaches zero, my class finally calls Dispose() on its
internal lock.
This seems ugly to me. There must be a better way. I know I could just skip
calling Dispose() on the lock and wait for it to be finalized, but who knows
when that'll happen? Maybe never.
Is there some kind of design pattern that's used in such cases?
Thanks.