﻿using System;
using System.Threading;

namespace Hydra.Framework.Threading
{
    /// <summary>
    /// Reader
    /// </summary>
    public class EnterUpgradableReader
        : IDisposable
    {
        #region Member
        /// <summary>
        /// Write Lock
        /// </summary>
        private readonly ReaderWriterLockSlim writeLock;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="EnterUpgradableReader"/> class.
        /// </summary>
        /// <param name="lockk">The lockk.</param>
        public EnterUpgradableReader(ReaderWriterLockSlim lockk)
        {
            writeLock = lockk;
            writeLock.EnterUpgradeableReadLock();
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// Upgrades this instance.
        /// </summary>
        /// <returns></returns>
        public EnterWriterLock Upgrade()
        {
            return new EnterWriterLock(writeLock);
        }
        #endregion

        #region IDisposable
        /// <summary>
        /// Performs application-defined taskQueue associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            writeLock.ExitUpgradeableReadLock();
        }
        #endregion
    }
}