Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent method from executing from different threads at the same time

Tags:

c#

Am I correct that the only way to prevent a method from being executed twice at the same time is by using a lock statement?

private object lockMethod = new object();

public void Method() {
    lock (lockMethod) {
        // work
    }
}

public void FromThread1() {
    Method();
}

public void FromThread2() {
    Method();
}

Of course I can also use MethodImpl(MethodImplOptions.Synchronized) what would be almost the same.

Are there other techniques?

like image 700
Oleg Vazhnev Avatar asked Jun 12 '12 00:06

Oleg Vazhnev


1 Answers

Am I correct that the only method to prevent method to execute twice at the same time is using lock statement?

No, but this is the "standard" way, and probably the best. That being said, typically you'd use a lock to synchronize access to specific data, not to a method as a whole. Locking an entire method will likely cause more blocking than necessary.

As for other methods, the System.Threading namespace contains many other types used for synchronization in various forms, including ReaderWriterLockSlim, Semaphore, Mutex, the Monitor class (which is what lock uses internally), etc. All provide various ways to synchronize data, though each is geared for a different scenario. In this case, lock is the appropriate method to use.

like image 97
Reed Copsey Avatar answered Sep 28 '22 04:09

Reed Copsey