This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-locking-cil/MfGames.Locking/NestableReadLock.cs

54 lines
1.7 KiB
C#

// <copyright file="NestableReadLock.cs" company="Moonfire Games">
// Copyright (c) Moonfire Games.
// This code is licensed under the MIT license.
// See LICENSE.md in the source or https://opensource.org/licenses/MIT
// </copyright>
namespace MfGames.Locking
{
using System;
using System.Threading;
/// <summary>
/// Defines a ReaderWriterLockSlim read-only lock.
/// </summary>
public class NestableReadLock : IDisposable
{
private readonly bool lockAcquired;
private readonly ReaderWriterLockSlim readerWriterLockSlim;
/// <summary>
/// Initializes a new instance of the <see cref="NestableReadLock" /> class.
/// </summary>
/// <param name="readerWriterLockSlim">The reader writer lock slim.</param>
public NestableReadLock(ReaderWriterLockSlim readerWriterLockSlim)
{
// Keep track of the lock since we'll need it to release the lock.
this.readerWriterLockSlim = readerWriterLockSlim;
// If we already have a read or write lock, we don't do anything.
if (readerWriterLockSlim.IsReadLockHeld
|| readerWriterLockSlim.IsUpgradeableReadLockHeld
|| readerWriterLockSlim.IsWriteLockHeld)
{
this.lockAcquired = false;
}
else
{
readerWriterLockSlim.EnterReadLock();
this.lockAcquired = true;
}
}
/// <inheritdoc />
public void Dispose()
{
if (this.lockAcquired)
{
this.readerWriterLockSlim.ExitReadLock();
}
}
}
}