Last active
February 22, 2022 12:13
-
-
Save bahusoid/dd91502076316bf40c597adc8a090486 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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