如果在同一实体上工作

如果在同一实体上工作

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

问题描述

我需要确保通过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
}

我该如何实现?

推荐答案

尝试一下,我不确定这些对象是否在.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 Async关键部分(如果在同一实体上工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:42