C#C
C#6mo ago
szkl0k

Deadlock's on singletione lifetime services

Hello.

I'm working on a system (service worker) that consumes different message brokers and some of the data is shared between them. Each message broker consumer is a BackgroundService. For the data sharing, I'm using a service which is registered as singleton. The service is internally using a non-threadsafe data structure and a ReaderWriterLockSlim. Of course, the data altering operations are doing the EnterWriteLock/ExitWriteLock and the readonly operations are doing the EnterReadLock/ExitReadLock.

Some initial operation which is a write enters the writelock, but the ExitWriteLock was not possible due to a AggregationException, which informed me that there was nothing to unlock. That seemed strange, but the main problem persisted even wihout the code that caused this problem.

Moving on, whenever I get to the EnterReadLock I'm getting deadlocked. When I replaced the ReaderWriterLockSlim in this service with an SemaphoreSlim and it seemd to work all right, but im still curious what was the problem and what are the best practices to such scenario.

EDIT:
The API of this service is async, so the logic in great simplification can look like this:
c#
try
{
  _lock.LockingHere();

  someOperation();
  await anotherOperation():
  finalOperation();
}
finally
{
  _lock.UnlockingHere()
}
Was this page helpful?