Suppose I process a large amount of input from multiple threads. I might want this data to act as a trigger for a specific action when certain criteria are met. However, the action is not repeated; therefore, the same trigger, fired twice in quick succession, should trigger only one action.
Using a simple bool flag to indicate whether an action is currently valid is not a reliable solution, as a race condition may arise, and two (or more) threads can still continue the same action at the same time. Of course, A bool in the lock statement of a synchronization object will work; but I generally prefer to avoid locking whenever possible *.
I am currently doing AutoResetEvent in these cases as essentially a form of atomic switch. The code usually looks something like this:
if (conditionMet && readyForAction.WaitOne(0)) { try { doAction(); } finally { readyForAction.Set(); } }
This works, but it seems to me that this may be more than an ideal use case for the AutoResetEvent class. Could you say that this is a suitable solution to this problem or does it make sense to use some other mechanism?
Update : as John pointed out , using Monitor.TryEnter as a locking strategy (instead of a simple lock , which I am roughly equivalent to Monitor.Enter ) is really quite simple:
if (conditionMet && Monitor.TryEnter(lockObject)) { try { doAction(); } finally { Monitor.Exit(lockObject); } }
However, I am very inclined to go with Henk's idea of using Interlocked . It seems as simple as possible.
source share