How to lock on an integer in C#?

后端 未结 14 2194
醉梦人生
醉梦人生 2020-12-05 14:44

Is there any way to lock on an integer in C#? Integers can not be used with lock because they are boxed (and lock only locks on references).

The scenario is as follo

14条回答
  •  春和景丽
    2020-12-05 14:54

    If it's a website then using an in-process lock probably isn't the best approach as if you need to scale the site out onto multiple servers, or add another site hosting an API (or anything else that would require another process accessing the same data to exist) then all your locking strategies are immediately ineffective.

    I'd be inclined to look into database-based locking for this. The simplest approach is to use optimistic locking with something like a timestamp of when the post was last updated, and to reject updates made to a post unless the timestamps match.

提交回复
热议问题