Regards, ManualResetEvent Utility

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

//This method is called on any thread other than the one that calls OnCompleted
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;
}

//This method is called exactly once.
protected internal virtual void OnCompleted(string result) {
    Result = result;
    isCompleted = true;
    Thread.MemoryBarrier();
    if (waitingCount == 0) {
        waiter.Dispose();
        waiter = null;
    } else
        waiter.Set();
}
+5
source share
2 answers

, , - waiter to null Dispose. , , .Net 4.0, , .

MSDN ManualResetEventSlim.Dispose , , , , Dispose . , , IDisposable ( ).

, , OnCompleted, , :

//This method is called exactly once.
protected internal virtual void OnCompleted(string result) {
    Result = result;
    isCompleted = true;

    waiter.Set();
    Thread.MemoryBarrier();
    if (waitingCount == 0) {
        waiter.Dispose();
    }
}

a >

+1

, , . OnCompleted, waitingCount > 0, isCompleted true, . - WaitForCompletion, , isCompleted true, . waiter.Dispose .

- SpinLock, ​​ , ManualResetEventSlim? , , , , , , . , , ManualResetEventSlim .

, ? "", .,.

+1

All Articles