I have a Singleton class that manages the connection to an external device. The idea of my application is that I need that external device to be presented all the time when the application is alive.
The Singleton has the following functionalities:
- Initialization, look for the device at the application startup time
- communicate with the external device, note that this can spread over multiple assemblies at multiple points.
- Close the connection when the application exits.
For the last part, I am thinking about putting the code inside Dispose method of the singleton class, to guarantee that the resource is always cleanup upon closing. But since I am using a Singleton, and since singleton life span will only be terminated when the application exits, there is no need to explicitly close the connection in Dispose since the connection will be close anyway.
So, the question is, should I put the close connection code inside Dispose method?
Implementing IDisposable alone doesn’t mean
Disposewill be called on exit.Not enough details to understand your application but if closing incorrectly leaves the device in a bad state than maybe a try/finally or as Moron suggested Application.Exit (depending on the application of course).
Even then you’re not guaranteed that code executes so maybe I’m not clear as to what you are trying to accomplish or what problem you are trying to solve.
Edit:
Per the OPs comment the best option (for his desire to have “cleanup” code execute without being specifically called and untestable) would be to put it in the deconstructor/finalizer. Note this is not guaranteed to run but should run in most circumstances without being called (unlike Dispose):