enyim/EnyimMemcached — Issue #99: Exceptions in CountdownEvent class
Author: Domo42
Created: 2012-03-07 13:30:31+00:00
State: open

Under heavy load I get exceptions thrown out of the CountdownEvent.Signal() method. I'm using the latest version from the master branch but it also happens in the issue76 branch.

I get this exceptions together using the couchbase 1.8 client library which is itself using EnyimMemcached lib.

Depending on timing there is either a ObjectDisposed exception, or a NullReferenceException during Signal() because the mre field is already disposed or null.

*As I see it, this is because of the shortcut in Wait() which immediately returns in case the counter is zero.*

Let me explain my thoughts: In my case, the error happens because Wait() and Signal() are called from two different threads at nearly the same time. The first thread calls Signal() which decrements the counter to 0. Now this thread gets shifted in the background and the second thread calling Wait() executes. Wait() immediately returns because count being already 0. The thread goes on and calls Dispose() because it assumes async operations have finished. Disposing the CountdownEvent class calls Close() on mre and eventually setting the field to null. Now the thread which originally called Signal() continues execution and finds mre to be either closed or already null (depending on timing).

Reducing the CountdownEvent.Wait() method without the counter being zero shortcut to

```
public void Wait()
{
this.mre.WaitOne();
}
```

fixed it for me without any noticeable performance impact.