如果在同一实体上工作

如果在同一实体上工作

本文介绍了如果在同一实体上工作,.Net Core 异步临界区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确保通过 Web API 访问的方法不能被多个调用同时访问,如果它适用于具有相同 id 的同一对象

I need to be sure that a method accessed via a web API cannot be accessed by multiple call at the same time if it work on the same object with the same id

我了解 SemaphoreSlim 的使用,但是一个简单的实现将锁定所有的临界区.但我需要锁定该部分仅当它适用于同一实体而不适用于 2 个不同的实体

I understand the use of SemaphoreSlim but a simple implemetation of that will lock the critical section for all. But I need that section locked only if it works on the same entity and not on 2 different

这是我的场景,一个用户开始工作,实体被创建并准备好被修改,然后一个或多个用户可以操作这个实体,但是这个操作的一部分必须在临界区或者它会导致数据不一致,当工作完成后,实体会从工作状态中移除并移至存档,只能只读访问

This is my scenario, an user start to work, the entity is created and is ready to be modified, then one or more user can manipulate this entity, but a part of this manipulation has to be in a critical section or it will lead to inconsistent data, when the work is finished, the entity will be removed from the work status and moved to and archive and can only be accessed readonly

包含该函数的类在应用程序启动时作为瞬态注入

The class which contains that function is injected as transient in the startup of the application

 services.AddTransient<IWorkerService>(f => new WorkerService(connectionString));
public async Task<int> DoStuff(int entityId)
{
  //Not Critical Stuff

  //Critical Stuff

  ReadObjectFromRedis();
  ManipulateObject();
  UpdateSqlDatabase();
  SaveObjectToRedis();

 //Not Critical Stuff
}

我怎样才能做到这一点?

How can I achieve that?

推荐答案

试试这个,我不确定这些对象是否在 .net-core 中可用

Try this, I'm not sure if those objects are available in .net-core

class Controller
{
    private static ConcurrentDictionary<int, SemaphoreSlim> semaphores = new ConcurrentDictionary<int, SemaphoreSlim>();

    public async Task<int> DoStuff(int entityId)
    {
        SemaphoreSlim sem = semaphores.GetOrAdd(entityId, ent => new SemaphoreSlim(0, 1));
        await sem.WaitAsync();
        try
        {
            //do real stuff
        }
        finally
        {
            sem.Release();
        }
    }
}

这篇关于如果在同一实体上工作,.Net Core 异步临界区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:43