带有监视器的 C# 中的 RAII 监视器

RAII Monitor in C# with Monitor

提问人:bpeikes 提问时间:5/26/2023 更新时间:5/26/2023 访问量:24

问:

一直在寻找 Monitor.TryEnter 的“包装器”类,这样我的代码看起来就不会很可怕。这样的事情已经存在了吗?我宁愿不自己滚动。

我在想:

// 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;
    }
}
C# RAII

评论


答: 暂无答案