Non blocking locking

前端 未结 4 1557
悲&欢浪女
悲&欢浪女 2021-01-04 19:28

I want to start some new threads each for one repeating operation. But when such an operation is already in progress, I want to discard the current task. In my scenario I ne

4条回答
  •  心在旅途
    2021-01-04 20:08

    One option would be to work with a reentrancy sentinel:

    You could define an int field (initialize with 0) and update it via Interlocked.Increment on entering the method and only proceed if it is 1. At the end just do a Interlocked.Decrement.

    Another option:

    From your description it seems that you have a Producer-Consumer-Scenario...

    For this case it might be helpful to use something like BlockingCollection as it is thread-safe and mostly lock-free...

    Another option would be to use ConcurrentQueue or ConcurrentStack...

提交回复
热议问题