Unloading Assemblies Loaded with Assembly.LoadFrom()
In order to check the time it takes to run GetTypes() after loading a DLL with Assembly.LoadFrom(), one might need to unload and reload the DLL. However, setting the Assembly reference to null is not enough to unload the assembly.
Unloading Assemblies Explicitly
To explicitly unload an assembly, you can use the AppDomain.Unload() method. Here's an example:
// Create a separate AppDomain to load the assembly AppDomain dom = AppDomain.CreateDomain("some"); // Load the assembly into the new AppDomain Assembly assembly = dom.LoadFrom(filePath); // Get the types from the assembly Type[] types = assembly.GetTypes(); // Unload the AppDomain, which will unload the assembly AppDomain.Unload(dom);
By unloading the AppDomain, the assembly and all its resources will be reclaimed by the garbage collector.
Using the Garbage Collector
While setting the Assembly reference to null does not explicitly unload the assembly, it makes it eligible for garbage collection. The garbage collector will eventually reclaim the resources allocated to the Assembly object and the assembly files will be unloaded from memory.
However, there is no way to explicitly call the garbage collector or force it to run immediately. It is a background process that runs when the system has idle time. Therefore, it is recommended to use AppDomain.Unload() if you want to unload an assembly explicitly.
The above is the detailed content of How Can I Explicitly Unload Assemblies Loaded with Assembly.LoadFrom()?. For more information, please follow other related articles on the PHP Chinese website!