Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hot Unload/Reload of a DLL used by an Application

Tags:

c#

I have an application that loads a DLL to execute a specific part of processing

Example : "Application.dll" loading "Process.dll"  

Process.dll is dynamically loaded at Runtime, using reflection, and not referenced in the application.

After processing is finished, the DLL needs to be recompiled on server and loaded back again later.
In order to do so, I need to free it, otherwise I get the following message : "Unable to copy file "Process.dll" to "Process.dll". The process cannot access the file 'Process.dll' because it is being used by another process."

So the question is : How to programmatically free/release/unload the Process.dll from my application before loading it back again. Of course,the whole point is to do this WITHOUT stopping the Application.

EDIT 1 :

A proposed solution goes like this :

AppDomain newDomain4Process = AppDomain.CreateDomain("newDomain4Process"); Assembly processLibrary = newDomain4Process.Load("Process.dll"); AppDomain.Unload(newDomain4Process); 

The problem I am still having is that, though I am giving the proper full path, I get a FileNotFound Exception. The answer to this post did not have the expected effect either.

EDIT 2 :

This post saved my life, here is the code :

class ProxyDomain : MarshalByRefObject     {         public Assembly GetAssembly(string AssemblyPath)         {             try             {                 return Assembly.LoadFrom(AssemblyPath);             }             catch (Exception ex)             {                 throw ex;             }         }     }     ProxyDomain pd = new ProxyDomain();    Assembly a = pd.GetAssembly(FullDLLPath); 

EDIT 3 :
I didn't get access to the AppDomain and unload it with the previous solution though. When I used the classic method of AppDomain Creation, I felt into Alexei's warning : AppDomain.Unload "seemed" to work, but the assembly was still loaded (Module View). So I still have my problem in some way, since I can't really unload the DLL efficiently.

like image 826
Mehdi LAMRANI Avatar asked Feb 03 '11 15:02

Mehdi LAMRANI


People also ask

Can you unload a DLL?

Short answer: No, it is impossible. Win32 doesn't provide an API to unload a DLL of another process. If a library is freed unexpectedly, the process will crash. This leads to a serious security hole as it breaks process protection mechanism.

How to unload DLL from process in c#?

Load("Process. dll"); AppDomain. Unload(newDomain4Process);


1 Answers

It's been quite a while since I looked at this but I'm fairly sure that you'd need to create a new AppDomain and then load the DLL inside there.

The reason is that you can't unload an Assembly by it self but you can unload an AppDomain that contains an Assembly.

like image 188
Hans Olsson Avatar answered Sep 29 '22 12:09

Hans Olsson