I'm running some Singleton code that is not thread safe, and takes some time to run. It can occasionally be called simultaneously by multiple users, so I'm using Monitor to handle the processing request queuing as below;
bool lockWasTaken = false;
try
{
Monitor.TryEnter(lockObject, ref lockWasTaken); // returns lockWasTaken = true if it can get a lock
if (!lockWasTaken)
{
log.Warn("Locked by existing request. Request is queued.");
Monitor.Enter(lockObject, ref lockWasTaken); // Goes into the queue to access the object
}
// Do the Singleton processing
}
catch(Exception ex)
{
log.Fatal(ex);
}
finally
{
if (lockWasTaken)
{
Monitor.Exit(lockObject);
}
}
This all works well. But what I would like to do is to be able to log how many queued requests there are. Is this possible?