Search code examples
c#async-awaitlockingasp.net-core-webapi.net-6.0

How implement exclusive locking of a resource inside a .NET 6 API?


I have a .NET 6 API endpoint that creates few independent resources and modifies a shared resource, but whenever there are concurrent HTTP requests API is faced with race condition while modifying the shared resource leading to unexpected results, the shared resource is an external resource out of my control, what is the best way to lock this resource at the application/API level and make concurrent requests wait for the lock to be released?

PS: I do not have any explicit multi-threading defined; consider it a vanilla .NET 6 API with a bunch of async-await methods that create/modify resources


Solution

  • If the "shared resource" is shared within an application instance, then you can use SemaphoreSlim for mutual exclusion. Your code would do an await semaphore.WaitAsync(); when it enters its critical section and a semaphore.Release(); (usually within a finally) when it exits its critical section.

    If the "shared resource" is external in the sense that it's shared between multiple application instances, then you would need to build a distributed lease system using, e.g., CosmosDb or Redis.