C#并发解决(lock)

如果是单机版,就是部署一个服务器站点的我们可以使用很经典的lock锁,或者queue队列,针对单机版

同步访问共享资源的首选技术是C#的lock关键字。这个关键字允许定义一段线程同步的代码语句。后进入的线程不会中断当前线程,而是停止自身下一步执行,线程在进入锁定范伟的时候必须获得l标记。比较安全(推荐的)的方式是声明私有的object成员来做为锁标示。 

 private static object sign = new object();

[HttpPost]
[Route("addfoodsupply")]
public IHttpActionResult Send([FromBody] FoodSupplyViewModel foodModel)
{
lock (sign)
{
var food = new fd_supply();
foodModel.order_number = _foodService.GetOrderNumber("食品申请");
food.UpdateFoodSupply(foodModel);
food.group_count = foodModel.group_count;
//food.group_count = _foodRepository.GetgroupCount(food.group_id);
_foodRepository.Insert(food);
_foodService.AddFoodSupply(food, foodModel.foodList);
return Ok(new { success = true, id = food.id });
}
}

posted @ 2020-06-03 17:08  艺洁  阅读(1586)  评论(0编辑  收藏  举报