Method lock in c#

后端 未结 4 1968
孤城傲影
孤城傲影 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:56

    If I understood correctly, you need something like this:

    static object lockMethod2 = new object();
    static object lockMethod3 = new object();
    
    public static void Method1() 
    {
        lock (lockMethod2)
        lock (lockMethod3)
        {
            //Body function
        }
    }
    
    public static void Method2() 
    {
        lock (lockMethod2)
        {
            //Body function
        }
    }
    
    public static void Method3() 
    {
        lock (lockMethod3)
        {
            //Body function
        }
    }
    

    This allows method3 to execute if method2 is running and vice versa, while method1 must wait for both. Of course, method2 and 3 will not run while 1 is running.

提交回复
热议问题