Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unloading the Assembly loaded with Assembly.LoadFrom()

I need to check the time amount to run GetTypes() after loading the dll. The code is as follows.

Assembly assem = Assembly.LoadFrom(file); sw = Stopwatch.StartNew(); var types1 = assem.GetTypes(); sw.Stop(); double time1 = sw.Elapsed.TotalMilliseconds; 

I'd like to unload and reload the dll to check the time to spend in running GetTypes() again.

  • How can I unload it? assem = null is good enough?
  • Is there an explicit way to call garbage collector to reclaim the resource allocated to assem?
like image 537
prosseek Avatar asked Jun 06 '11 21:06

prosseek


People also ask

How to unload loaded assembly c#?

To unload an assembly in the . NET Framework, you must unload all of the application domains that contain it. To unload an application domain, use the AppDomain. Unload method.

What is assembly C#?

C# Assembly is a standard library developed for . NET. Common Language Runtime, CLR, MSIL, Microsoft Intermediate Language, Just In Time Compilers, JIT, Framework Class Library, FCL, Common Language Specification, CLS, Common Type System, CTS, Garbage Collector, GC.

What is AppDomain C#?

The AppDomain class implements a set of events that enable applications to respond when an assembly is loaded, when an application domain will be unloaded, or when an unhandled exception is thrown. Advantages. A single CLR operating system process can contain multiple application domains.


Video Answer


2 Answers

Can you use another AppDomain?

AppDomain dom = AppDomain.CreateDomain("some");      AssemblyName assemblyName = new AssemblyName(); assemblyName.CodeBase = pathToAssembly; Assembly assembly = dom.Load(assemblyName); Type [] types = assembly.GetTypes(); AppDomain.Unload(dom); 
like image 159
Rene de la garza Avatar answered Oct 08 '22 01:10

Rene de la garza


Instead of using LoadFrom() or LoadFile() you can use Load with File.ReadAllBytes(). With this it does not use the assembly file but will read it and use read data.

Your code will then look like

Assembly assem = Assembly.Load(File.ReadAllBytes(filePath)); sw = Stopwatch.StartNew(); var types1 = assem.GetTypes(); sw.Stop(); double time1 = sw.Elapsed.TotalMilliseconds; 

From here We cannot unload the file unless all the domains contained by it are unloaded.

Hope this helps.:)

like image 44
Hardik Avatar answered Oct 07 '22 23:10

Hardik