How to Dispose IDisposable Custom IDataPortalProxy?

How to Dispose IDisposable Custom IDataPortalProxy?

Old forum URL: forums.lhotka.net/forums/t/2711.aspx


Yang posted on Monday, April 16, 2007

We have a custom IDataPortalProxy that communicates with a JMS server. The actual JMS client implementation uses several threads to maintain its connection to the servers in the event of a failover. Threads are alive until we explicitly close the connection, otherwise our application will not terminate. The connection needs to be closed explicitly so we implemented a JMSProxy that is IDisposable and have the connections closed upon disposing.

Currently the DataPortal module does not dispose the proxy when application tries to close. What we did was we added a Close method in the DataPortal module that contains a call to dispose the proxy if it implements IDisposable. This to us is not an elegant solution as our app needs to know about the DataPortal. Having a shared destructor or a module finalizer should be helpful in this case.

We are looking for a more elegant solution to do this and would like to ask this forum if anyone had already done it.

Thank you very much.

RockfordLhotka replied on Monday, April 16, 2007

When do you want to call Dispose()?

After each DataPortal.Fetch() call for example? Or when the client application is shutting down?

If you need to call it after each data portal invocation, your data portal proxy can do that internally.

If you need to do it before the client app shuts down, that's obviously much harder, and is ultimately unreliable. .NET is not deterministic about how static/Shared code modules are destroyed, and there's no real way to guarantee any code will run during app shutdown.

Obviously there are many reasons an app may shut down - the user closes it, the process crashes, Task manager is used to close the app, or to stop the process cold, the system could be shutting down, you could have an unhandled top-level exception, etc. It is technically not possible to guarantee that your dispose code will run in all these cases.

Your best bet is probably exactly what you are doing. Try to handle as many shutdown cases as possible and call a Dispose/Close method in those cases - then just hope the other shutdown cases don't occur too often...

Yang replied on Tuesday, April 17, 2007

Hi Rocky,

Thanks for the quick response. Good to see that you are back. I do hope that all is well on your side.

We are trying to dispose the proxy when the client application is shutting down. Unfortunately the JMS connection needs to be explicitly closed otherwise all is good. We will just stick with our implementation for now.

I sure hope .NET will have something like a class shared finalizer for cleanup of shared resources some day. Delphi has this capability built in. Calling in Anders Hejlsberg ... :)

Regards,

Yang

Copyright (c) Marimer LLC