views:

173

answers:

2

My application generally running on 10-20 threads and these threads sending events to the GUI to the update certain controls almost every seconds.

When the user close the application middle of these, all updates related with these events causes several random crashes. Mostly ObjectDisposedException and NullReferenceException.

Since the events already thrown but not handled yet by the .NET Framework, they are not in a state where I can cancel them.

I'm not quite sure about the best way to handle this. Currently I'm just swallowing exceptions the exceptions.

+4  A: 

A few options:

  • when the app starts closing (FormClosing?), you could start cleanly exiting the threads (via a flag somewhere)
  • presumably to talk to your UI, you are raising events that are handled by the UI (which handles synchronization etc) - keep a flag, and (if it is safe to do do) simply drop events if the flag has been set (again, because you are exiting)
  • when exiting, have the UI unsubscribe from events
Marc Gravell
+1  A: 

In addition to Marc Gravell's suggestions, here's a few more things:

  • From any point, you can check Environment.HasShutdownStarted before doing anything that could cause an ObjectDisposed exception
  • If you're accessing any windows forms, you can check .IsDisposed (all forms and controls have it)
Orion Edwards
I didn't know Environment.HasShutdownStarted sounds promising, I've already implemented FormClosing flag, but next time I'll keep this in mind. Bigger problem though testing if the fixes worked or not :) Since it's a bit hard to get this error.
dr. evil