In C#, assemblies loaded using Assembly.LoadFrom() need to be explicitly unloaded to free up memory and release resources held by the assembly.
To unload an assembly, you can use the AppDomain.Unload method. This method unloads the specified AppDomain, which in turn unloads all the assemblies loaded within that AppDomain. For example:
// Create a new AppDomain and load the assembly AppDomain dom = AppDomain.CreateDomain("some"); AssemblyName assemblyName = new AssemblyName(); assemblyName.CodeBase = pathToAssembly; Assembly assembly = dom.Load(assemblyName); // Get the types from the assembly Type[] types = assembly.GetTypes(); // Unload the AppDomain AppDomain.Unload(dom);
Calling assem = null alone does not guarantee that the assembly will be unloaded immediately. The garbage collector will still need to run to reclaim the unreferenced resources. You cannot explicitly call the garbage collector in C#.
However, you can force the garbage collector to run sooner by calling the GC.Collect method. This method triggers a garbage collection cycle and attempts to reclaim all unreachable objects. While GC.Collect can be used to improve performance in some scenarios, it's generally not recommended to rely on it heavily, as it can introduce pauses in your application.
The above is the detailed content of How to Unload Assemblies Loaded with Assembly.LoadFrom() in C#?. For more information, please follow other related articles on the PHP Chinese website!