Lock() in a static method

后端 未结 2 838
情歌与酒
情歌与酒 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

    The concept of lock() is to use an existing-object it can reference and use to control whether access is granted.

    static object SpinLock = new object();
    
    lock(SpinLock)
    {
       //Statements
    }
    

    When the execution leaves the lock() block the reference is released and any other threads waiting to execute the code block can proceed (one at a time, of course).

提交回复
热议问题