We know it's easy to load and unload DLLs in C + +, and LoadLibrary and FreeLibrary allow you to easily load DLLs in your program and unload them anywhere.
In C # We can also use Assembly.loadfile to implement dynamic load DLLs, but when you try to uninstall, you will be surprised to find that assembly does not provide any way to uninstall. This is due to the automatic garbage collection machine of managed code
The system will do this, so C # does not provide a function to release resources, everything is done by garbage collection.
but we can implement the load domain offload through the application domain (AppDomain), which shows how to use it as follows. when the AppDomain is unloaded, all resources in that environment will also be recycled.
For more details on the AppDomain, refer to MSDN.
The following is the code using System.Collections.Generic for dynamically unloading DLLs using the AppDomain;
Using System.Text;
Using System.Threading;
Using System.Reflection;
Namespace Unloaddll
{
Class Program
{
static void Main (string[] args)
{
String callingdomainname = Appdomain.currentdomain.friendlyname;//thread.getdomain (). FriendlyName;
Console.WriteLine (Callingdomainname);
AppDomain ad = Appdomain.createdomain ("DLL Unload test");
Proxyobject obj = (proxyobject) ad. CreateInstanceFromAndUnwrap (@ "UnloadDll.exe", "Unloaddll.proxyobject");
Obj. LoadAssembly ();
Obj. Invoke ("Testdll.class1", "Test", "It s a Test");
AppDomain.Unload (AD);
obj = null;
Console.ReadLine ();
}
}
Class Proxyobject:marshalbyrefobject
{
Assembly Assembly = null;
public void loadassembly ()
{
Assembly = Assembly.loadfile (@ "TestDLL.dll");
}
public bool Invoke (string FullClassName, String methodName, params object[] args)
{
if (assembly = = null)
return false;
Type TP = assembly. GetType (FullClassName);
if (TP = = NULL)
return false;
MethodInfo method = TP. GetMethod (MethodName);
if (method = = null)
return false;
Object obj = activator.createinstance (TP);
Method. Invoke (obj, args);
return true;
}
}
}Note:1. To allow an object to pass through the AppDomain boundary, you must inherit the MarshalByRefObject class, otherwise it cannot be used by another AppDomain. 2. Each thread has a default AppDomain, which can be obtained by Thread.getdomain ()
C#.net how to dynamically load and unload an assembly (. dll or. exe)