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?
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, theMonitor class(which is whatlockuses internally), etc. All provide various ways to synchronize data, though each is geared for a different scenario. In this case,lockis the appropriate method to use.