Kettch19
Kettch19

Reputation: 404

Release a file lock on a COM DLL that has been instantiated via `CreateObject`

I have a .Net 4 WinForms app that generates a DLL, calls CreateObject on the generated DLL then calls one of several methods that the DLL contains. The DLL is eventually used by a separate app. This WinForms app is just to generate and test the DLL hence why it can generate the DLL multiple times.

The problem lies in the fact that calling CreateObject on the DLL locks the file to the process. The next time the DLL is generated it can't overwrite the previous DLL file on disk without closing the app completely and starting it again.

I've tried Marshal.ReleaseComObject, executing the CreateObject in a separate AppDomain, even setting the variable holding the COM object to a different COM object via CreateObject, manually calling GC.Collect() and a whole host of other things but none result in unlocking the file.

The code flow is basically (simplified and generic names, etc.):

...
' Compile and generate DLL that is COM enabled and works fine
...

Dim foo As Object = CreateObject("Bar.Foo")
foo.callMethod()

...
' Succeeds or fails then continues
...

...
' Clean up and remove the generated DLL     
foo = Nothing
File.Delete("C:\myassembly.dll")
...

Pretty standard usage. So my question is: is there a way to release a file lock on a COM DLL that has been instantiated via CreateObject without killing the process?

Note: this is a continuation of this original issue. I now have the DLL registering without locking the file but now the issue is with the CreateObject call not the DLL registration.

Upvotes: 0

Views: 662

Answers (1)

Roman Ryltsov
Roman Ryltsov

Reputation: 69706

You should be doing Marshal.ReleaseComObject(foo) in order to release the COM object, followed by P/Invoke CoFreeUnusedLibraries in order to unload those DLL loaded through COM and unused any longer.

Upvotes: 1

Related Questions