I have a method in a multi-threaded application and I’d like the following behavior when this method is invoked:
- If no other threads are currently executing the method, execute it.
- If another thread is currently executing the method then exit the method without executing it.
The lock statement in C# is useful for waiting until a thread has completed execution, but I don’t want to serialize access to this method but rather bypass executing said method if it is being executed by another thread.
I suppose I don’t understand… if it should only be called by one thread at a time, why are multiple threads calling it to begin with?
Anyway, you can use Monitor.TryEnter(). It doesn’t block and returns
falseif it fails to acquire a lock. In that case you can just return from the function.