There is this DB-connection-like object that my web application will need. It is pretty slow to create and will be used rarely, so I would like to keep only a single instance of it around. If several requests need it at the same time, they will lock()
the object and serialize their access.
To make things more fun the object is an IDisposable and can be closed. Naturally, I'll avoid writing code that closes it, but... you know... better safe than sorry, right?
So, the naïve approach would be to implement it something like this:
private static DBClass _Instance;
private static object _DBLock = new object();
public DBClass GetDB()
{
if ( _Instance == null )
lock (_DBLock )
if ( _Instance == null )
_Instance = CreateInstance();
lock (_Instance)
if ( _Instance.Disposed )
_Instance = CreateInstance();
return _Instance;
}
It will then be used like:
lock (var Conn = Global.GetDB() )
{
// Use Conn here.
}
This will probably work most of the time, but I see an opening that could be exploited - if two threads call this at the same time, they get the same instance at the same time, and then one could still Dispose()
it before the other acquires a lock()
on it. Thus - later code fails. Checking for Disposed
at every place that uses it also seems awkward. In fact, lock()
ing it seems awkward too, but the instance isn't inherently thread-safe so there's nothing I can do about it.
How would you implement this?