Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

ReaderWriteLockDisposable.cs

namespace Nop.Core.ComponentModel;

/// 
/// Provides a convenience methodology for implementing locked access to resources. 
/// 
/// 
/// Intended as an infrastructure class.
/// 
public partial class ReaderWriteLockDisposable : IDisposable
{
    #region Fields

    protected bool _disposed;
    protected readonly ReaderWriterLockSlim _rwLock;
    protected readonly ReaderWriteLockType _readerWriteLockType;

    #endregion

    #region Ctor

    /// 
    /// Initializes a new instance of the  class.
    /// 
    /// The readers–writer lock
    /// Lock type
    public ReaderWriteLockDisposable(ReaderWriterLockSlim rwLock, ReaderWriteLockType readerWriteLockType = ReaderWriteLockType.Write)
    {
        _rwLock = rwLock;
        _readerWriteLockType = readerWriteLockType;

        switch (_readerWriteLockType)
        {
            case ReaderWriteLockType.Read:
                _rwLock.EnterReadLock();
                break;
            case ReaderWriteLockType.Write:
                _rwLock.EnterWriteLock();
                break;
            case ReaderWriteLockType.UpgradeableRead:
                _rwLock.EnterUpgradeableReadLock();
                break;
        }
    }

    #endregion

    #region Utilities

    /// 
    /// Protected implementation of Dispose pattern.
    /// 
    /// Specifies whether to disposing resources
    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
            return;

        if (disposing)
        {
            switch (_readerWriteLockType)
            {
                case ReaderWriteLockType.Read:
                    _rwLock.ExitReadLock();
                    break;
                case ReaderWriteLockType.Write:
                    _rwLock.ExitWriteLock();
                    break;
                case ReaderWriteLockType.UpgradeableRead:
                    _rwLock.ExitUpgradeableReadLock();
                    break;
            }
        }

        _disposed = true;
    }

    #endregion

    #region Methods

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

    #endregion
}