Allows using SemaphoreSlim locks by a given key of any type.
You can use the KeyedLock NuGet as shown below.
publicclassFoo{privateKeyedLocker<string>_locker=newKeyedLocker<string>();publicvoidDoSomethingWithLock(stringkeyToLock){_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.
publicclassFoo{privateHashedKeyedLock<long,int>_locker=newHashedKeyedLocker<long,int>(long x =>(int)(x%10));// limit to 10 locks in memorypublicvoidDoSomethingWithLock(longkeyToLock){_locker[keyToLock].Wait();try{//do something...}finally{_locker[keyToLock].Release();}}}Some of the ideas for this repo were taken from this blog post.