Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit a method if another thread is executing it

I have a method in a multi-threaded application and I'd like the following behavior when this method is invoked:

  1. If no other threads are currently executing the method, execute it.
  2. 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.

like image 499
Scott Mitchell Avatar asked Sep 13 '12 18:09

Scott Mitchell


1 Answers

You can do this using Monitor.TryEnter, but perhaps more simply: Interlocked:

int executing; // make this static if you want this one-caller-only to
               // all objects instead of a single object
void Foo() {
    bool won = false;
    try {
        won = Interlocked.CompareExchange(ref executing, 1, 0) == 0;
        if(won) {
           // your code here
        }
    } finally {
        if(won) Interlocked.Exchange(ref executing, 0);
    }

}
like image 184
Marc Gravell Avatar answered Oct 14 '22 19:10

Marc Gravell