如何:卸载应用程序域
注意
本文特定于 .NET Framework。 它不适用于 .NET 的较新版本实现,包括 .NET 6 及更高版本。
完成使用应用程序域时,可使用 AppDomain.Unload 方法将其卸载。 Unload 方法会正常关闭指定的应用程序域。 卸载过程中,任何新线程都无法访问该应用程序域,并且会释放所有特性于应用程序域的数据结构。
加载到应用程序域中的所有程序集都会被移除,无法再使用。 如果应用程序域中的程序集不特定于域,则程序集的数据会保留在内存中,直到整个进程关闭。 除了关闭整个进程,没有机制可以卸载非特定于域的程序集。 在某些情况下,卸载应用程序域的请求会不起作用,并导致 CannotUnloadAppDomainException。
以下示例新建名为 MyDomain
的应用程序域,并将一些信息输出至控制台,然后卸载应用程序域。 请注意,代码随后会尝试将卸载的应用程序域的友好名称输出至控制台。 此操作生成一个异常,该异常由程序结尾处的 try/catch 语句处理。
示例
using namespace System;
using namespace System::Reflection;
ref class AppDomain2
{
public:
static void Main()
{
Console::WriteLine("Creating new AppDomain.");
AppDomain^ domain = AppDomain::CreateDomain("MyDomain", nullptr);
Console::WriteLine("Host domain: " + AppDomain::CurrentDomain->FriendlyName);
Console::WriteLine("child domain: " + domain->FriendlyName);
AppDomain::Unload(domain);
try
{
Console::WriteLine();
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 (AppDomainUnloadedException^ e)
{
Console::WriteLine(e->GetType()->FullName);
Console::WriteLine("The appdomain MyDomain does not exist.");
}
}
};
int main()
{
AppDomain2::Main();
}
using System;
using System.Reflection;
class AppDomain2
{
public static void Main()
{
Console.WriteLine("Creating new AppDomain.");
AppDomain domain = AppDomain.CreateDomain("MyDomain", null);
Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine("child domain: " + domain.FriendlyName);
try
{
AppDomain.Unload(domain);
Console.WriteLine();
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 (AppDomainUnloadedException e)
{
Console.WriteLine(e.GetType().FullName);
Console.WriteLine("The appdomain MyDomain does not exist.");
}
}
}
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)
AppDomain.Unload(domain)
Try
Console.WriteLine()
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(e.GetType().FullName)
Console.WriteLine("The appdomain MyDomain does not exist.")
End Try
End Sub
End Class