How to: Unload an Application Domain 

When you have finished using an application domain, unload it using the System.AppDomain.Unload method. The Unload method gracefully shuts down the specified application domain. During the unloading process, no new threads can access the application domain, and all application domain–specific data structures are freed.

Assemblies loaded into the application domain are removed and are no longer available. If an assembly in the application domain is domain-neutral, data for the assembly remains in memory until the entire process is shut down. There is no mechanism to unload a domain-neutral assembly other than shutting down the entire process. There are situations where the request to unload an application domain does not work and results in a CannotUnloadAppDomainException.

The following example creates a new application domain called MyDomain, prints some information to the console, and then unloads the application domain. Note that the code then attempts to print the friendly name of the unloaded application domain to the console. This action generates an exception that is handled by the try/catch statements at the end of the program.


Imports System
Imports System.Reflection
Class AppDomain2
   Public Shared Sub Main()
      Console.WriteLine("Creating new AppDomain.")
      Dim domain As AppDomain = AppDomain.CreateDomain("MyDomain", Nothing)
      Console.WriteLine(("Host domain: " + AppDomain.CurrentDomain.FriendlyName))
      Console.WriteLine(("child domain: " + domain.FriendlyName))
         Console.WriteLine(("Host domain: " + AppDomain.CurrentDomain.FriendlyName))
         ' The following statement creates an exception because the domain no longer exists.
         Console.WriteLine(("child domain: " + domain.FriendlyName))
      Catch e As AppDomainUnloadedException
         Console.WriteLine("The appdomain MyDomain does not exist.")
      End Try
   End Sub 'Main
End Class 'AppDomain2

See Also