英文:
How implement exclusive locking of a resource inisde a .NET 6 API?
问题
我有一个.NET 6 API端点,用于创建一些独立的资源并修改共享资源,但每当有并发的HTTP请求时,API都会面临竞争条件,而修改共享资源导致意外结果,共享资源是我无法控制的外部资源,最佳方法是在应用程序/API级别锁定此资源,并使并发请求等待锁定释放?
PS:我没有定义任何显式的多线程操作;将其视为一个普通的.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
答案1
得分: 1
如果“共享资源”在应用程序实例内共享,则可以使用SemaphoreSlim
进行互斥。当进入关键部分时,您的代码将执行await semaphore.WaitAsync();
,当退出关键部分时,通常在finally
中执行semaphore.Release();
。
如果“共享资源”是外部的,即在多个应用程序实例之间共享,则需要使用例如CosmosDb或Redis构建分布式租约系统。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论