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
}
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With