Lock() in a static method

后端 未结 2 943
情歌与酒
情歌与酒 2021-02-12 13:04

I have a multi threaded application that writes to a settings xml file using a static method. I want to avoid that the file is being updated twice at the same time (causing acce

2条回答
  •  不要未来只要你来
    2021-02-12 13:52

    You should create a separate, static lock object and use that. DO NOT USE A STRING! Strings are automatically interned and there will be only one instance of each programmatically declared string so you can't guarantee exclusive access to the lock.

    You should do this:

    public class A {
        private static Object LOCK = new Object();
    
        private static void foo() {
            lock(LOCK) {
                // Do whatever
            }
        }
    }
    

    (The syntax may be incorrect; I'm a Java person mostly but the same rules about locking and String interning apply to C#)

    The lock keyword enforces a mutual exclusion lock: only one thread can lock any particular object at a time. If a second thread calls foo then it will block until the first thread has exited the lock block.

    Take home messages: for a static method lock on a private static variable. Don't lock on Strings or typeof(...) because you cannot guarantee that no-one else is using that object. Always lock on an object you know is not touched by anyone else by making it private and making it new.

提交回复
热议问题