It is easy to load and uninstall DLL in C. LoadLibrary and FreeLibrary allow you to easily load the DLL in the program and then uninstall it anywhere. In C #, we can also use Assembly. LoadFile to dynamically load the DLL, but when you try to uninstall it, you will be surprised to find that Assembly does not provide any uninstall methods. This is because the automatic garbage collection mechanism of the managed code will do this, So C # does not provide a function to release resources, and all is done by garbage collection.
This raises a problem. The DLL loaded with Assembly may only be released at the end of the program. This also means that the loaded DLL cannot be updated during the program running. This function is necessary in some programming. Consider that you are using the reflection mechanism to write a program to view the details of all functions in the DLL, the program provides a menu for users to select the DLL file. In this case, the program needs to be able to uninstall the DLL. Otherwise, the program must be restarted once the user obtains the new DLL version, re-select to load the DLL file, this design is intolerable to the user.
C # also provides a way to dynamically uninstall DLL through AppDomain. AppDomain is an environment for Independent Application Execution. When the AppDomain is uninstalled, all resources in the environment will be recycled. For more information about AppDomain, see MSDN. The following code uses AppDomain to dynamically uninstall DLL,
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", "Its 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, it must inherit the MarshalByRefObject class; otherwise, it cannot be used by other AppDomains.
2. Each Thread has a default AppDomain, which can be obtained through Thread. GetDomain ().