如何在.NET 6 API 中实现资源的独占锁定?

huangapple go评论62阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月16日 13:42:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76487253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定