Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method lock in c#

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
    }
}
like image 879
Emanuele Mazzoni Avatar asked Feb 20 '13 10:02

Emanuele Mazzoni


People also ask

Why do we use lock statement in C?

The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.

How is lock keyword used?

The LOCK keyword is used when there are several consecutive output operations that contain input fields. This keyword has no parameters. If this keyword is not specified, the workstation user can type data into a field when a subsequent output operation sends data to the display.

What is lock in c3?

The lock keyword is used to get a lock for a single thread. A lock prevents several threads from accessing a resource simultaneously. Typically, you want threads to run concurrently. Using the lock in C#, we can prevent one thread from changing our code while another does so.

What is lock in multithreading?

A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first.


1 Answers

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.

like image 146
Paolo Tedesco Avatar answered Oct 16 '22 09:10

Paolo Tedesco