How to lock on an integer in C#?

后端 未结 14 2243
醉梦人生
醉梦人生 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 15:01

    You should use a sync object like this:

    public class YourForm
    {
        private static object syncObject = new object();
    
        public void Moderate()
        {
            lock(syncObject)
            {
                // do your business
            }
        }
    }
    

    But this approach shouldn't be used in a web app scenario.

提交回复
热议问题