© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•7mo ago•
7 replies
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:
try
{
  _lock.LockingHere();

  someOperation();
  await anotherOperation():
  finalOperation();
}
finally
{
  _lock.UnlockingHere()
}
try
{
  _lock.LockingHere();

  someOperation();
  await anotherOperation():
  finalOperation();
}
finally
{
  _lock.UnlockingHere()
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Microsoft's DI Hierarchically controlled lifetime manager? [Answered]
C#CC# / help
4y ago
Very strange deadlock on Exception.ToString
C#CC# / help
7mo ago
✅ ASP.NET Core: Confusion with builder.Services.AddTransient() and App Lifetime Management
C#CC# / help
2y ago
✅ How Scope lifetime works
C#CC# / help
2y ago