RAII Monitor in C# with Monitor

29 Views Asked by At

Been looking for a "wrapper" class for Monitor.TryEnter, so that my code doesn't look horrendous. Does anything like this already exist? I would rather not roll my own.

I was thinking something like:

// Example usage
Object objToLock = new Object();

using(var lock = RAIIMonitor.TryEnter(obj, Timespan.FromSeconds(2)))
{
     if(lock.HasLock)
    {
       // Do stuff
    }

}

// Example class
class RAIIMonitor: IDisposable
{
    private bool disposed = false;

    public bool HasLock = false;
    public object Object = null;

    public static RAIIMonitor TryEnter(object obj, Timespan timeout)
    {
         return new RAIIMonitor(obj, timeout);
    }

    private RAIIMonitor(object obj, Timespan timeout)
    {
        Object = obj;
        Monitor.TryEnter(obj, timeout, ref HasLock);
    }

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
             if(HasLock && Object != null)
             {
                 Monitor.Exit(Object);
             }
        }

        disposed = true;
    }
}
0

There are 0 best solutions below