Method Lock in C #

I have one class with these three methods. This class is used by many threads. I would like Method1 to wait if Method2 and / or Method3 work 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 } } 
+7
source share
4 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, methods 2 and 3 will not work while 1 is executing.

+8
source

The current implementation of your lock is completely useless, because each thread will block another object.
Locking is usually done using the readonly field, which is initialized only once.
For example, you can easily block several 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 } } } 
+8
source

I would ReaderWriterLockSlim ( http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx )

Like read operations, method 2 and method 3 can occur in parallel, while Method1 (for example, a write operation) must wait for these operations to complete. This is not a common concurrency read / write situation, but the logic is similar.

 public class Class1 { private ReaderWriterLockSlim methodLock = new ReaderWriterLockSlim(); public static void Method1() { methodLock.EnterWriteLock(); try { //Body function } finally { cacheLock.ExitWriteLock(); } } public static void Method2() { methodLock.EnterReadLock(); try { //Body function } finally { methodLock.ExitReadLock(); } } public static void Method3() { methodLock.EnterReadLock(); try { //Body function } finally { methodLock.ExitReadLock(); } } } 
+6
source

If you are multithreading, then lock should be available for all threads. Therefore, in this case, your locks must be static for static methods to see this.

Your current setup will make a new lock object for each thread. Therefore, providing synchronization now.

+3
source

All Articles