Skip to content

Latest commit

 

History

History
57 lines (48 loc) · 1.82 KB

README.md

File metadata and controls

57 lines (48 loc) · 1.82 KB

KeyedLocks

Allows using SemaphoreSlim locks by a given key of any type.

Build Status

Usage

You can use the KeyedLock NuGet as shown below.

NuGet

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();
        }
    }
}

Resources

Some of the ideas for this repo were taken from this blog post.