Method lock in c#

.net, c#, multithreading, thread-safety

Solution

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.

Problem

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 suggestions? ``` public class Class1 { public static void Method1() { Object lockThis = new Object(); lock (lockThis) { //Body function } } public static void Method2() { //Body function } public static void Method3() { //Body function } } ```

Original source