Allows using SemaphoreSlim locks by a given key of any type.
You can use the KeyedLock NuGet as shown below.
public class Foo
{
private KeyedLocker<string> _locker = new KeyedLocker<string>();
public void DoSomethingWithLock(string keyToLock)
{
_locker[keyToLock].Wait();
try
{
//do something...
}
finally
{
_locker[keyToLock].Release();
}
}
}
If your code will contain many keys, consider using the HashedKeyedLocker with a hash function to minimize the nubmer of SemaphoreSlim objects that will be held in memory.
public class Foo
{
private HashedKeyedLock<long, int> _locker = new HashedKeyedLocker<long, int>(long x => (int)(x % 10)); // limit to 10 locks in memory
public void DoSomethingWithLock(long keyToLock)
{
_locker[keyToLock].Wait();
try
{
//do something...
}
finally
{
_locker[keyToLock].Release();
}
}
}
Some of the ideas for this repo were taken from this blog post.