53 lines
1.7 KiB
C#
53 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();
|
|
}
|
|
}
|
|
}
|
|
}
|