How to lock on an integer in C#?

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

    This option builds on the good answer provided by configurator with the following modifications:

    1. Prevents the size of the dictionary from growing uncontrollably. Since, new posts will get new ids, your dictionary of locks will grow indefinitely. The solution is to mod the id against a maximum dictionary size. This does mean that some ids will have the same lock (and have to wait when they would otherwise not have to), but this will be acceptable for some dictionary size.
    2. Uses ConcurrentDictionary so there is no need for a separate dictionary lock.

    The code:

    internal class IdLock
    {
        internal int LockDictionarySize
        {
            get { return m_lockDictionarySize; }
        }
        const int m_lockDictionarySize = 1000;
        ConcurrentDictionary m_locks = new ConcurrentDictionary();
        internal object this[ int id ]
        {
            get
            {
                object lockObject = new object();
                int mapValue = id % m_lockDictionarySize;
                lockObject = m_locks.GetOrAdd( mapValue, lockObject );
                return lockObject;
            }
        }
    }
    

    Also, just for completeness, there is the alternative of string interning: -

    1. Mod the id against the maximum number of interned id strings you will allow.
    2. Convert this modded value to a string.
    3. Concatenate the modded string with a GUID or namespace name for name collision safety.
    4. Intern this string.
    5. lock on the interned string. See this answer for some information:

    The only benefit of the string interning approach is that you don't need to manage a dictionary. I prefer the dictionary of locks approach as the intern approach makes a lot of assumptions about how string interning works and that it will continue to work in this way. It also uses interning for something it was never meant / designed to do.

提交回复
热议问题