Skip to content

doug144/KeyedLocks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.