Exit a method if another thread is executing it

后端 未结 4 2140
既然无缘
既然无缘 2021-02-07 13:18

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 m
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-07 13:55

    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);
        }
    
    }
    

提交回复
热议问题