
Unload Assemblies From an Application Domain
by Enrico Sabbadin
Posted November 21, 2003
Technology Toolbox: VB.NET
Level: Intermediate
The .NET Framework has introduced the concept of application domains, which act as lightweight processes. More than one application domain can coexist in the same OS process. A default application domain is created when the Common Language Runtime (CLR) is first loaded into a process. Your code generally runs within this default application domain (with the exception of ASP.NET-based applications, which recycle application domains).
The CLR loads assemblies into application domains transparently the first time a type contained in the assembly is referenced within a JIT-compiled piece of code. You also can force the CLR to load a specific assembly manually using calls such as Assembly.LoadFrom or Assembly.Load.
Note, however, that there is no corresponding call to unload, such as Assembly.Unload. Once an assembly has been loaded into an application domain, the assembly remains loaded (meaning the assembly file is locked on the disk as well) until the entire application domain is unloaded (calling the Unload static method on the AppDomain class):
AppDomain.Unload(myAppDomain)
Two objects cannot communicate directly if they run in two different application domains. Their communication must pass through .NET Remoting instead. As a consequence, classes that must be passed outside the application domain in which they were created must inherit from MarshalByRefObject.
You need to add a bit of code in a separate application domain when you need to unload the assembly once you've executed a specific task on it. You would need to do this, for instance, when developing VS.NET add-ins, in order to avoid locking your own assemblies into the VS.NET process (so you cannot rebuild them).
Back to top
|