Saleem
Saleem

Reputation: 730

How to release a .Net DLL called in VB6 application from memory?

I have an old VB6 project where I call .Net library I created. I'm still in the unit test phase for this dll, so the problem is that every time I update my dll and make the running VB6 app recognize it, I'm forced to close the app to replace the old dll version with the new one. So I think the dll is being loaded in memory when first called and not being released until I exit the app calling it. Is there anyway to release the DLL from within VB6 app?

Upvotes: 1

Views: 569

Answers (1)

Hans Passant
Hans Passant

Reputation: 941465

COM supports unloading servers that are no longer used. The underlying api call is CoFreeUnusedLibraries() and the DllCanUnloadNow() entrypoint in the server, automatically called by the COM infrastructure. The exact moment in time that this happens is generally unpredictable, ought to already be a hangup if you want to replace DLLs on demand.

But that doesn't work for a [ComVisible] .NET assembly. A restriction imposed by the CLR, a .NET assembly can only be unloaded when the AppDomain is destroyed. Created the first time you create an object from the .NET assembly. The AppDomain will not be destroyed until program exit, thus keeping a lock on the DLL.

It is technically possible to make this happen anyway, you'd have to expose a shim class in one assembly that forwards the calls to another class that's implemented in another assembly. That you load in another AppDomain. Quite painful to do, and slow because of the required appdomain boundary marshaling. A significant hangup is that you can't get a good signal to destroy that AppDomain. You have to make it explicit with a method you expose that the client code can call. An out-of-process server would be another approach, also slow and painful in .NET, it requires COM+ hosting with the ServicedComponent class. Lots of reasons to not want to need this.

Upvotes: 5

Related Questions