Exit a method if another thread is executing it

后端 未结 4 2136
既然无缘
既然无缘 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 14:14

    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 false if it fails to acquire a lock. In that case you can just return from the function.

提交回复
热议问题