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

前端 未结 8 721
无人共我
无人共我 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:57

    The safest and shortest way is to create a private, static field of type Object that is only used for locking (think of it as a "pad-lock" object). Use this and only this field to lock on as this prevent other types from locking up your code when then lock on the same type that you do.

    If you lock on the type itself there is risk that another type will also decide to lock on your type and this could create deadlocks.

    Here is an example:

    class Test
    {
        static readonly Object fooLock = new Object();
        static String foo;
    
        public static String Foo
        {
            get { return foo; }
            set
            {
                lock (fooLock)
                {
                    foo = value;
                }
            }
        }
    }
    

    Notice that I have create a private, static field for locking foo - I use that field to lock the write operations on that field.

提交回复
热议问题