Handling ObjectDisposedException and similar exceptions during process termination?

My application, usually running on 10-20 threads, and these threads sending events to the GUI for updates are monitored almost every second.

When the user closes the application in the middle, all updates related to these events cause several random crashes. Mostly ObjectDisposedExceptionand NullReferenceException.

Since events that have already been processed by the .NET Framework but have not yet been processed, they are not in a state where I can cancel them.

I'm not quite sure of a better way to handle this. Currently, I just swallow exceptions, exceptions.

+3
source share
2 answers

Several variants:

  • when the application starts to close ( FormClosing?), you can start a clean shutdown of the threads (through some flag)
  • presumably, to talk to your user interface, you raise events that are processed by the user interface (which handles synchronization, etc.) - keep the flag, and (if it's safe to do) just delete the events if the flag is set (again, because what are you going out)
  • When you exit it, the user interface is unsubscribed from events
+4
source

In addition to the proposals of Mark Gravell , here are a few more things:

  • Environment.HasShutdownStarted, -, ObjectDisposed
  • , .IsDisposed ( )
+1

Source: https://habr.com/ru/post/1707466/


All Articles