Currently I'm struggeling with the implementation of SemaphoreSlim
for "locking" "parts" of a method which has to be thread-safe. My problem is, that implementing this without having an overload of exception handling is very hard. Because when an exception is thrown before the "lock" will be released, it will stay there forever.
Here is an example:
private SemaphoreSlim _syncLock = new SemaphoreSlim(1);
private IDictionary<string, string> dict = new Dictionary<string, string>();
public async Task ProcessSomeThing(string input)
{
string someValue = await GetSomeValueFromAsyncMethod(input);
await _syncLock.WaitAsync();
dict.Add(input, someValue);
_syncLock.Release();
}
This method would throw an exception if input has the same value more than once, because an item with the same key will be added twice to the dictionary and the "lock" will not be released.
Let's assume i have a lot of _syncLock.Release();
and _syncLock.Release();
, it is very hard to write the try-catch
or .ContainsKey
or some thing else. This would totally blow up the code... Is it possible to release the lock always when an Exception
get's thrown or some term is leaved?
Hope it is clear what I'm asking/looing for.
Thank you all!