I'm using an application that synchronizes threads using ManualResetEvent. FxCop told me to dispose those objects. I found the following discussion which told me the same:
Do I need to Dispose() or Close() an EventWaitHandle?
But I don't know when to dispose an instance of a ManualResetEvent.
The following simplified code demonstrates the problem:
private void btn_Click(object sender, EventArgs e)
{
var mre = new ManualResetEvent(false);
new Thread(() => this.SetEvent(mre)).Start();
for (int i = 0; i < 10; ++i)
{
new Thread(() => this.WaitFor(mre)).Start();
}
}
private void SetEvent(ManualResetEvent manualResetEvent)
{
Thread.Sleep(10000);
manualResetEvent.Set();
}
private void WaitFor(ManualResetEvent manualResetEvent)
{
manualResetEvent.WaitOne();
}
The problem is that multiple instances of the ManualResetEvent exist and multiple threads are waiting for each instance.
If I memorize the instances in a list I don't know when to dispose it. Disposing it after WaitOne()-call will dispose it multiple times and maybe it will be disposed while other threads are still waiting.
The thread that created the event doesn't have any reference to it. The setter-thread should not dispose it because there are other threads waiting for this MRE. Each waiting thread isn't able to dispose it as mentioned before.
So the question is: When should this ManualResetEvent be disposed?