views:

140

answers:

2

I have two ManualResetEvents, which I use to pass control back and forth between two threads. Essentially a coroutine.

Because the coroutine holds disposable objects (ManualResetEvents are wait handles), it should implement disposable. Also, it should dispose those ManualResetEvents when it is disposed. But, because only one thread runs at a time, one of them is (almost) always waiting on one of the handles.

What is the specified behavior if I dispose both ManualResetEvents? Will the waiting thread be stuck forever, or will disposing terminate the wait? What if I call .Set() first?

A: 

It is bad practice to imply on implementation of ManualResetEvents. Create supervisor class that owns by events, and using refcounter pattern (each thread increase/decrease usage) dispose supervisor when counter meets 0.

Dewfy
I already know the threads are safe to dispose. The problem is actually performing the dispose. I need to guarantee no thread is deadlocked.
Strilanc
The way when you dispose event, while it is used, grants unpredictable behavior on different platforms or different loading of CPU. But applying correct pattern resolve this question - don't dispose event while exists possibility that it can be used.
Dewfy
A: 

I recently had a similar problem, and decided to replace wait handles with a monitor and the wait/pulse pattern described by Marc Gravell here and here. Because the monitor class is completely managed, you don't have to worry about disposing any resources. Of course, you still might need to think through your shut-down procedure, but the wait/pulse pattern is a little more flexible for adding things like a shut down flag.

Don Kirkby