AppDomain.Unload(AppDomain) 方法

定义

注意

Creating and unloading AppDomains is not supported and throws an exception.

卸载指定的应用程序域。

public static void Unload(AppDomain domain);
[System.Obsolete("Creating and unloading AppDomains is not supported and throws an exception.", DiagnosticId="SYSLIB0024", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public static void Unload(AppDomain domain);

参数

domain
AppDomain

要卸载的应用程序域。

属性

例外

domainnull

仅限 .NET Core 和 .NET 5 及更高版本:在所有情况下。

-或-

domain 未能卸载。

在卸载进程期间出错。

示例

下面的代码示例演示如何卸载应用程序域。

using System;
using System.Reflection;
using System.Security.Policy;
class ADUnload
{
    public static void Main()
    {

        //Create evidence for the new appdomain.
        Evidence adevidence = AppDomain.CurrentDomain.Evidence;

        // Create the new application domain.
        AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence);

                Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
                Console.WriteLine("child domain: " + domain.FriendlyName);
        // Unload the application domain.
        AppDomain.Unload(domain);

        try
        {
        Console.WriteLine();
        // Note that the following statement creates an exception because the domain no longer exists.
                Console.WriteLine("child domain: " + domain.FriendlyName);
        }

        catch (AppDomainUnloadedException e)
        {
        Console.WriteLine("The appdomain MyDomain does not exist.");
        }
    }
}

注解

在 .NET Framework 2.0 及更高版本中,有一个专用于卸载应用程序域的线程。 这可以提高可靠性,尤其是在托管.NET Framework时。 当线程调用 Unload时,目标域标记为要卸载。 专用线程尝试卸载域,并且域中的所有线程都中止。 如果线程未中止(例如,因为它正在执行非托管代码,或者因为它正在执行块 finally ),则在一段时间后, CannotUnloadAppDomainException 会在最初称为 Unload的线程中引发 。 如果无法中止的线程最终结束,则不会卸载目标域。 因此,在 .NET Framework 2.0 及更高版本中,domain无法保证卸载,因为可能无法终止执行线程。

备注

在某些情况下,调用 Unload 会导致即时 CannotUnloadAppDomainException,例如,如果在终结器中调用它。

中的 domain 线程使用 Abort 方法终止,该方法在线程中引发 ThreadAbortException 。 尽管线程应立即终止,但它可以在 子句中 finally 继续执行不可预知的时间。

适用于

产品 版本 (已过时)
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5 (6, 7, 8, 9)
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

另请参阅