HOW TO:卸載應用程式定義域
當您結束應用程式定義域的使用時,可以使用 System.AppDomain.Unload 方法將之卸載。 Unload 方法可以順利關閉指定的應用程式定義域。 在卸載處理序期間,新的執行緒將無法存取應用程式定義域,而且所有應用程式定義域特定的資料結構都將釋放出來。
已載入至應用程式定義域的組件會被移除,並且無法再使用。 如果應用程式定義域中的組件是定義域中性的,那麼除非整個處理序都已關閉,否則組件的資料會保留在記憶體中。 卸載定義域中性組件的唯一機制便是關閉整個處理序。 有時候卸載應用程式定義域的要求並不會成功,而且會產生 CannotUnloadAppDomainException。
下列範例建立新的應用程式定義域 (名為 MyDomain) 將某些資訊列印到主控台後,再卸載應用程式定義域。 請注意,接下來程式碼將嘗試列印卸載應用程式定義域的名稱到主控台。 這個動作將會在程式結束時產生一則由 Try/Catch 陳述式處理的例外狀況。
範例
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)
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
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);
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.");
}
}
}
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();
}