Skip to content

Instantly share code, notes, and snippets.

@bahusoid
Last active February 22, 2022 12:13
Show Gist options
  • Save bahusoid/dd91502076316bf40c597adc8a090486 to your computer and use it in GitHub Desktop.
Save bahusoid/dd91502076316bf40c597adc8a090486 to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
using NHibernate.Cache;
using Pipelines.Sockets.Unofficial.Threading;
//Depends on nuget package: https://www.nuget.org/packages/Pipelines.Sockets.Unofficial
namespace YourNamespace
{
public class MutexSlimCacheLock : ICacheLock
{
private readonly MutexSlim _mutexSlim;
public MutexSlimCacheLock(int lockTimeoutMilliseconds)
{
_mutexSlim = new MutexSlim(lockTimeoutMilliseconds);
}
public void Dispose()
{
}
public IDisposable ReadLock()
{
return CreateLock();
}
public IDisposable WriteLock()
{
return CreateLock();
}
public Task<IDisposable> WriteLockAsync()
{
return CreateAsyncLock();
}
public Task<IDisposable> ReadLockAsync()
{
return CreateAsyncLock();
}
private IDisposable CreateLock()
{
var lockToken = _mutexSlim.TryWait();
if (lockToken)
return lockToken;
throw NewTimeoutException();
}
private async Task<IDisposable> CreateAsyncLock()
{
var lockToken = await _mutexSlim.TryWaitAsync().ConfigureAwait(false);
if (lockToken)
return lockToken;
throw NewTimeoutException();
}
private static TimeoutException NewTimeoutException()
{
return new TimeoutException("Timeout obtaining lock.");
}
}
public class MutexSlimCacheFactory : ICacheReadWriteLockFactory
{
public ICacheLock Create()
{
//TODO: provide your timeout here
return new MutexSlimCacheLock((int) TimeSpan.FromMinutes(60).TotalMilliseconds);
}
}
}
Configuration cfg = ...
cfg.SetProperty(Environment.CacheReadWriteLockFactory, typeof(MutexSlimCacheFactory).AssemblyQualifiedName);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment