Background
I am working on implementing a derived class of a database accessor that should only allow one thread at a time access to the database. But this question should be applicable to any form of single thread access with the Disposable pattern.
In Stephen Cleary's blog he shows how to implement a mutex with an IDisposable patern, this is almost the idea.
On MSDN's website they show how to use the IDisposable
pattern in a derived class.
In this answer about best practices of SQlite db in android it is proposed to open the SQLite db, and never close it, but use a type of delegate to maintain concurrency; this I do not like, but it gave me the idea of what follows.
The program
The base class which throws exception if more than one thread tries to access it:
class BaseClass : IDisposable
The derived class which implements the lock:
class DerivedClass : BaseClass
{
private static Semaphore _mutex = new Semaphore(1, 5);
public DerivedClass
{
_mutex.WaitOne();
}
protected override void Dispose(bool disposing)
{
if (disposed)
return;
Question
Where should the _mutex.Release()
be called? Before or after the base.Dispose()
?
i.e. option 1:
_mutex.Release();
disposed = true;
base.Dispose(disposing);
or option 2:
disposed = true;
base.Dispose(disposing);
_mutex.Release();
MSDN says to free any unmanaged objects before calling base.Dispose
, which makes it feel that the release should also happen before, like option 1. And it's MSDN, I'm sure they know the best.
But, option 1 opens the door for a thread to access the base class before it is Disposed (at least it looks like it). Which makes me feel that option 2 is the correct implementation.
I have tried both implementations, and both work; but I am unsure which one will keep on working.
Can you please also explain why the one or the other.