防止客户端从API获取相同的记录

问题描述

我有一个非常简单的.NET核心API,可以为客户执行任务。当客户端请求任务时,API会更新其状态并将任务返回给客户端。但是我注意到,如果多个客户端同时请求一个任务,那么他们最终将获得相同的任务。以下是相关的控制器代码

        [HttpPost("next",Name = "RequestJob")]
        public ActionResult<QueJobReadDto> RequestJob(Robot robot)
        {
            var job = _repository.RequestJob();
            var registeredJob = _repository.RegisterJob(robot.RobotName,job);
            _repository.SaveChanges();
            return Ok(_mapper.Map<QueJobReadDto>(registeredJob));
        }

如您所见,使用了两种方法:“ RequestJob”和“ RegisterJob”。 RequestJob查找状态为“ In Que”的记录,RegisterJob将记录的状态更新为“ In Progress”。以下是相关的实现:

        public QueJob RequestJob()
        {
            
            return _context.QueJobs
                .Where(queJob => queJob.Status == "In Que")
                .OrderBy(queJob => queJob.JobGuid)
                .ToList()
                .FirstOrDefault();
        }
        public QueJob RegisterJob(string worker,QueJob qj)
        {
            qj.Status = "In Progress";
            qj.Start = DateTime.UtcNow;
            qj.Worker = worker;
            qj.JobGuid = qj.JobGuid;
            _context.Update(qj);
            return _context.QueJobs.Find(qj.JobGuid);
        }

我的问题是:我该如何结合使用这些方法,以使客户端永远无法完成相同的任务?

解决方法

如果要试用经济版,请将其添加到控制器顶部

private const int LockTimeoutInMilliseconds = 100;
private static readonly object LockObject = new object();

然后

[HttpPost("next",Name = "RequestJob")]
public ActionResult<QueJobReadDto> RequestJob(Robot robot)
{
  if (!Monitor.TryEnter(LockObject,LockTimeoutInMilliseconds))
  {
     // return an approriate error messsage
  }

  try
  {
    var job = _repository.RequestJob();
    var registeredJob = _repository.RegisterJob(robot.RobotName,job);
    _repository.SaveChanges();
    return Ok(_mapper.Map<QueJobReadDto>(registeredJob));
  }
  finally
  {
    Monitor.Exit(LockObject); // ensure that the lock is released.
  }
}