There doesn't seem anything particularly problematic in the code you've given, which would suggest that there is perhaps something in the code you've not shown that's causing the problem. I'm assuming that the worker
you're using is part of your codebase (rather than part of the .NET BCL like BackgroundWorker
?) It may be worth posting the code for that, in case there is an issue there that's causing the problem.
If for example, the same worker is used repeatedly from multiple threads (or has a bug in which Completed
can be raised more than once for the same piece of work), then if the worker uses the "usual" means for invoking an event handler, i.e.:
var handler = Completed;
if (handler != null)
{
handler(...);
}
You could have an instance where var handler = Completed;
is executed before the finally
clause (and so before the completedHandler
has been detached from the Completed
event), but handler(...)
is called after the using(...)
block is exited (and so after the ManualResetEvent
has been disposed). Your event handler will then be executed after waitHandle
is disposed, and the exception you are seeing will be thrown.