Prevent the simultaneous start of a method from different threads

I will correct that the only way to prevent the method from running simultaneously is with the help of an instruction lock?

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)something that would be almost the same.

Are there other methods?

+5
source share
1 answer

I assume that the only way to prevent the method from running simultaneously at the same time is to use the lock statement?

No, but this is the “standard” way and probably the best. In this case, a lock is usually used to synchronize access to specific data, and not to the method as a whole. Locking the entire method is likely to result in a larger lock than necessary.

, System.Threading , , ReaderWriterLockSlim, Semaphore, Mutex, Monitor class ( , lock ) .. , . lock - .

+9

All Articles