Similar to this question I have a class with a private ManualReset event:
class A {
private ManualResetEvent mre = new ManualResetEvent(true);
private void Method(){
//do something
mre.Reset();
}
public bool WaitForItem(int timeout){
try{
return mre.WaitOne(timeout)
}catch(ObjectDisposedException){
return false;
}
}
public void Dispose(){
mre.Dispose();
}
}
How can I check that when Dispose
is called WaitForItem
method returns false, and doesn't block waiting.
The code is something similar to:
A a = new A(1);
a.Method();
bool finished = true;
Thread t1 = new Thread(() =>
{
finished = a.WaitForItem(Timeout.Infinite);
});
Thread t2 = new Thread(() =>
{
a.Dispose();
});
t1.Start();
t2.Start();
t1.Join();
t2.Join();
The code blocks in waiting an item forever (at t1.Join()
). I understood that calling Close
, which is also a mean of disposing an object, doesn't affect the state of the handle, but how can I exit the method with false (catching an ObjectDisposedException
) ?
Even though instead of calling a.Dispose()
on the second thread calling another method which Disposes the ManualResetEvent the call to WaitOne() it's blocked.
ManualResetEventSlim
and use the Wait(CancellationToken) method. Just change yourDispose
method to set the cancellation token before disposing the MRE. Honestly, though, you need to re-think your design. Something like this really shouldn't be necessary.