How to lock on an integer in C#?

后端 未结 14 2278
醉梦人生
醉梦人生 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:57

    I would personally go with either Greg's or Konrad's approach.

    If you really do want to lock against the post ID itself (and assuming that your code will only ever be running in a single process) then something like this isn't too dirty:

    public class ModeratorUtils
    {
        private static readonly HashSet _LockedPosts = new HashSet();
    
        public void ModeratePost(int postId)
        {
            bool lockedByMe = false;
            try
            {
                lock (_LockedPosts)
                {
                    lockedByMe = _LockedPosts.Add(postId);
                }
    
                if (lockedByMe)
                {
                    // do your editing
                }
                else
                {
                    // sorry, can't edit at this time
                }
            }
            finally
            {
                if (lockedByMe)
                {
                    lock (_LockedPosts)
                    {
                        _LockedPosts.Remove(postId);
                    }
                }
            }
        }
    }
    

提交回复
热议问题