How to lock on an integer in C#?

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

    You need a whole different approach to this.

    Remember that with a website, you don't actually have a live running application on the other side that responds to what the user does.

    You basically start a mini-app, which returns the web-page, and then the server is done. That the user ends up sending some data back is a by-product, not a guarantee.

    So, you need to lock to persist after the application has returned the moderation page back to the moderator, and then release it when the moderator is done.

    And you need to handle some kind of timeout, what if the moderator closes his browser after getting the moderation page back, and thus never communicates back with the server that he/she is done with the moderation process for that post.

    0 讨论(0)
  • 2020-12-05 15:13

    I like doing it like this

    public class Synchronizer {
        private Dictionary<int, object> locks;
        private object myLock;
    
        public Synchronizer() {
            locks = new Dictionary<int, object>();
            myLock = new object();
        }
    
        public object this[int index] {
            get {
                lock (myLock) {
                    object result;
                    if (locks.TryGetValue(index, out result))
                        return result;
    
                    result = new object();
                    locks[index] = result;
                    return result;
                }
            }
        }
    }
    

    Then, to lock on an int you simply (using the same synchronizer every time)

    lock (sync[15]) { ... }
    

    This class returns the same lock object when given the same index twice. When a new index comes, it create an object, returning it, and stores it in the dictionary for next times.

    It can easily be changed to work generically with any struct or value type, or to be static so that the synchronizer object does not have to be passed around.

    0 讨论(0)
提交回复
热议问题