Loading and unloading DLLs in C + + is an easy task, 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 because the automatic garbage collection mechanism of managed code does this, so C # does not provide a function to free up resources, all from garbage collection.
This raises the question that DLLs loaded with assembly may be released only at the end of the program, which also means that the loaded DLL cannot be updated while the program is running. And this function is necessary in some programming, considering you are using reflection mechanism to write a view of all the functions of the DLL program, the program provides a menu allows the user to select the DLL file, you need to let the program can unload the DLL, or once the user re-get the new version of the DLL, You must restart the program and re-select the load DLL file so that the design is intolerable to the user.
C # also provides a way to implement a dynamic unload DLL, implemented through an AppDomain. An AppDomain is an environment in which an application is executed independently, and all resources in that environment will be reclaimed when the AppDomain is unloaded. For more information about the AppDomain, refer to MSDN.
Here's the code for dynamically unloading DLLs using the AppDomain:
Using System;
Using System.Collections.Generic;
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;
}
}
}
Attention:
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 ()
AppDomain in detail two "go"-c# dynamically load and unload DLLs