Best C# solution for multithreaded threadsafe read/write locking?

前端 未结 8 821
无人共我
无人共我 2021-01-01 05:08

What is the safest (and shortest) way do lock read/write access to static members in a multithreaded environment in C#?

Is it possible to do the thread

8条回答
  •  情书的邮戳
    2021-01-01 05:58

    class LockExample {
        static object lockObject = new object();
        static int _backingField = 17;
    
        public static void NeedsLocking() {
            lock(lockObject) {
                // threadsafe now
            }
        }
    
        public static int ReadWritePropertyThatNeedsLocking {
            get {
                lock(lockObject) {
                    // threadsafe now
                    return _backingField;
                }
            }
            set {
                lock(lockObject) {
                    // threadsafe now
                    _backingField = value;
                }
            }
        }
    }
    

    lock on an object specifically created for this purpose rather than on typeof(LockExample) to prevent deadlock situations where others have locked on LockExample's type object.

    Is it possible to do the threadsafe locking & unlocking on class level (so I don't keep repeating lock/unlock code every time static member access is needed)?

    Only lock where you need it, and do it inside the callee rather than requiring the caller to do the locking.

提交回复
热议问题