https://github.com/doug144/keyedlocks
A NuGet library for c# locking by a given key
https://github.com/doug144/keyedlocks
async csharp csharp-library lock locking netstandard netstandard20 nuget semaphoreslim
Last synced: 2 months ago
JSON representation
A NuGet library for c# locking by a given key
- Host: GitHub
- URL: https://github.com/doug144/keyedlocks
- Owner: doug144
- License: mit
- Created: 2019-02-24T19:35:33.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2019-03-04T19:25:43.000Z (over 6 years ago)
- Last Synced: 2025-04-01T00:43:42.434Z (2 months ago)
- Topics: async, csharp, csharp-library, lock, locking, netstandard, netstandard20, nuget, semaphoreslim
- Language: C#
- Homepage:
- Size: 27.3 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# KeyedLocks
Allows using [SemaphoreSlim](https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=netstandard-2.0)
locks by a given key of any type.[](https://dev.azure.com/douglasgross/KeyedLock/_build/latest?definitionId=1&branchName=master)
## Usage
You can use the [KeyedLock NuGet](https://www.nuget.org/packages/KeyedLock/) as shown below.
[](https://www.nuget.org/packages/KeyedLock/)
````csharp
public class Foo
{
private KeyedLocker _locker = new KeyedLocker();
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](/KeyedLock/HashedKeyedLocker.cs) with a hash function to minimize the nubmer of
[SemaphoreSlim](https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=netstandard-2.0)
objects that will be held in memory.````csharp
public class Foo
{
private HashedKeyedLock _locker = new HashedKeyedLocker(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();
}
}
}
````
## Resources
Some of the ideas for this repo were taken from [this blog post](https://www.tabsoverspaces.com/233703-named-locks-using-monitor-in-net-implementation).