Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclusive lock using key in .NET

I have used the lock statement in C# to exclusively execute a piece of code. Is there a way to do same based on a key.

for e.g.:

lock(object, key)
{
//code-here
}

I have a method which has some piece of code that is not thread-safe, but only if the key (string) happens to be same in two parallel executions. Is there a way to somehow accomplish this in .NET ?

If there is a way then we can have parallel executions if the key being used in the parallel executions is different and could improve performance.

like image 583
Brij Avatar asked Oct 17 '25 03:10

Brij


2 Answers

Put lock objects into dictionary indexed by the key - Dictionary<string, object> and grab objects by key to lock.

If you need to dynamically add new key/lock object pairs make sure to lock around the dictionary access, otherwise if after construction you only read values from dictionary no additional locking is needed.

like image 151
Alexei Levenkov Avatar answered Oct 18 '25 16:10

Alexei Levenkov


I create a library called AsyncKeyedLock which solves the problem. Internally it uses a ConcurrentDictionary and SemaphoreSlim objects.

In case you're using asynchronous code you can use:

using (await _locker.LockAsync(myObject.Id))
{
   ...
}

or if you're using synchronous code:

using (_locker.Lock(myObject.Id))
{
   ...
}
like image 24
Mark Cilia Vincenti Avatar answered Oct 18 '25 16:10

Mark Cilia Vincenti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!