I have a class that allows other threads to wait for an operation to complete using ManualResetEventSlim. (Operations are usually short)
This class does not have an explicit lifetime, so there is no single place where I can easily close the event.
Instead, I want to close the event as soon as it ends with & mdash, as soon as it is signaled, and after any pending threads wake up.
For performance reasons, I would prefer not to use a lock.
Is this code thread safe and can it run faster?
volatile bool isCompleted;
volatile int waitingCount;
ManualResetEventSlim waiter = new ManualResetEventSlim();
public void WaitForCompletion() {
if (isCompleted)
return;
Interlocked.Increment(ref waitingCount);
Thread.MemoryBarrier();
if (!isCompleted)
waiter.Wait();
if (0 == Interlocked.Decrement(ref waitingCount)) {
waiter.Dispose();
waiter = null;
}
return;
}
protected internal virtual void OnCompleted(string result) {
Result = result;
isCompleted = true;
Thread.MemoryBarrier();
if (waitingCount == 0) {
waiter.Dispose();
waiter = null;
} else
waiter.Set();
}
SLaks source
share