Method lock in c#

后端 未结 4 1964
孤城傲影
孤城傲影 2021-02-19 05:16

I have one class with these three methods. This class is used by many threads. I would like the Method1 to wait, if Method2 and/or Method3 are running in any threads. Any sugges

4条回答
  •  [愿得一人]
    2021-02-19 05:43

    The current implementation of your lock is completely useless, because every thread will lock on a different object.
    Locking is usually done with a readonly field that is initialized only once.
    Like this, you can easily lock multiple methods:

    public class Class1
    {
        private static readonly object _syncRoot = new object();
    
        public static void Method1() 
        {
            lock (_syncRoot)
            {
                //Body function
            }
        }
    
        public static void Method2() 
        {
            lock (_syncRoot)
            {
                //Body function
            }
        }
    
        public static void Method3() 
        {
            lock (_syncRoot)
            {
                //Body function
            }
        }
    }
    

提交回复
热议问题