AppDomain 类

表示应用程序域,它是一个应用程序在其中执行的独立环境。无法继承此类。

**命名空间:**System
**程序集:**mscorlib(在 mscorlib.dll 中)

语法

声明
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
<ComVisibleAttribute(True)> _
Public NotInheritable Class AppDomain
    Inherits MarshalByRefObject
    Implements _AppDomain, IEvidenceFactory
用法
Dim instance As AppDomain
[ClassInterfaceAttribute(ClassInterfaceType.None)] 
[ComVisibleAttribute(true)] 
public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory
[ClassInterfaceAttribute(ClassInterfaceType::None)] 
[ComVisibleAttribute(true)] 
public ref class AppDomain sealed : public MarshalByRefObject, _AppDomain, IEvidenceFactory
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.None) */ 
/** @attribute ComVisibleAttribute(true) */ 
public final class AppDomain extends MarshalByRefObject implements _AppDomain, IEvidenceFactory
ClassInterfaceAttribute(ClassInterfaceType.None) 
ComVisibleAttribute(true) 
public final class AppDomain extends MarshalByRefObject implements _AppDomain, IEvidenceFactory

备注

应用程序域(由 AppDomain 对象表示)为执行托管代码提供隔离、卸载和安全边界。

  • 使用应用程序域隔离可能终止进程的任务。如果正在执行任务的 AppDomain 的状态变得不稳定,则可以卸载 AppDomain,但不会影响进程。当进程必须不重新启动而长时间运行时,这一点很重要。还可使用应用程序域隔离不应共享数据的任务。

  • 如果程序集被加载到默认应用程序域中,则当进程运行时将无法从内存中卸载该程序集。但是,如果打开另一个应用程序域来加载和执行程序集,则卸载该应用程序域时也会同时卸载程序集。使用此技术最小化长时间运行的进程的工作集,这些进程偶尔会使用大型 DLL。

多个应用程序域可以在一个进程中运行;但是,在应用程序域和线程之间没有一对一的关联。多个线程可以属于一个应用程序域,尽管给定的线程并不局限于一个应用程序域,但在任何给定时间,线程都在一个应用程序域中执行。

应用程序域通过使用 CreateDomain 方法来创建。AppDomain 实例用于加载和执行程序集 (Assembly)。当不再使用 AppDomain 时,可以将它卸载。

AppDomain 类实现一组事件,这些事件使应用程序可以在加载程序集、要卸载应用程序域或引发未处理的异常时进行响应。

有关使用应用程序域的更多信息,请参见 应用程序域

此类实现 MarshalByRefObject_AppDomainIEvidenceFactory 接口。

在任何情况下都不应创建 AppDomain 对象的可远程控制的包装。这样做可发布对该 AppDomain 的远程引用,将诸如 CreateInstance 方法向远程访问公开,并有效损坏该 AppDomain 的代码访问安全性。连接到远程 AppDomain 的恶意客户端可以获得对 AppDomain 本身可访问的所有资源的访问权。您不应为任何以下类型创建可远程控制的包装:扩展 MarshalByRefObject 的类型和实现恶意客户端可用来绕过安全系统的方法的类型。

警告

AppDomainSetup.DisallowCodeDownload 属性的默认值为 false。此设置对于服务不安全。若要防止服务下载部分受信任的代码,请将此属性设置为 true

Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE 平台说明: 不支持将程序集加载到非特定域的代码区域以供多个应用程序域使用。

主题 位置
如何:将程序集加载到应用程序域中 .NET Framework:编程基础
如何:配置应用程序域 .NET Framework:编程基础
如何:卸载应用程序域 .NET Framework:编程基础
如何:创建应用程序域 .NET Framework:编程基础
如何:配置应用程序域 .NET Framework:编程基础
如何:将程序集加载到应用程序域中 .NET Framework:编程基础
如何:创建应用程序域 .NET Framework:编程基础
如何:卸载应用程序域 .NET Framework:编程基础

示例

此示例显示如何创建新的 AppDomain,在该新建 AppDomain 中实例化类型,以及与该类型的对象通信。此外,此示例还显示如何卸载导致对象被垃圾回收的 AppDomain

Imports System
Imports System.Reflection
Imports System.Threading

Module Module1
    Sub Main()

        ' Get and display the friendly name of the default AppDomain.
        Dim callingDomainName As String = Thread.GetDomain().FriendlyName
        Console.WriteLine(callingDomainName)

        ' Get and display the full name of the EXE assembly.
        Dim exeAssembly As String = [Assembly].GetEntryAssembly().FullName
        Console.WriteLine(exeAssembly)

        ' Construct and initialize settings for a second AppDomain.
        Dim ads As New AppDomainSetup()
        ads.ApplicationBase = _
            "file:///" + System.Environment.CurrentDirectory
        ads.DisallowBindingRedirects = False
        ads.DisallowCodeDownload = True
        ads.ConfigurationFile = _
            AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

        ' Create the second AppDomain.
        Dim ad2 As AppDomain = AppDomain.CreateDomain("AD #2", Nothing, ads)

        ' Create an instance of MarshalbyRefType in the second AppDomain. 
        ' A proxy to the object is returned.
        Dim mbrt As MarshalByRefType = CType( _
            ad2.CreateInstanceAndUnwrap(exeAssembly, _
                 GetType(MarshalByRefType).FullName), MarshalByRefType)

        ' Call a method on the object via the proxy, passing the default 
        ' AppDomain's friendly name in as a parameter.
        mbrt.SomeMethod(callingDomainName)

        ' Unload the second AppDomain. This deletes its object and 
        ' invalidates the proxy object.
        AppDomain.Unload(ad2)
        Try
            ' Call the method again. Note that this time it fails because 
            ' the second AppDomain was unloaded.
            mbrt.SomeMethod(callingDomainName)
            Console.WriteLine("Sucessful call.")
        Catch e As AppDomainUnloadedException
            Console.WriteLine("Failed call; this is expected.")
        End Try

    End Sub
End Module

' Because this class is derived from MarshalByRefObject, a proxy 
' to a MarshalByRefType object can be returned across an AppDomain 
' boundary.
Public Class MarshalByRefType
    Inherits MarshalByRefObject

    '  Call this method via a proxy.
    Public Sub SomeMethod(ByVal callingDomainName As String)

        ' Get this AppDomain's settings and display some of them.
        Dim ads As AppDomainSetup = AppDomain.CurrentDomain.SetupInformation
        Console.WriteLine("AppName={0}, AppBase={1}, ConfigFile={2}", _
            ads.ApplicationName, ads.ApplicationBase, ads.ConfigurationFile)

        ' Display the name of the calling AppDomain and the name 
        ' of the second domain.
        ' NOTE: The application's thread has transitioned between 
        ' AppDomains.
        Console.WriteLine("Calling from '{0}' to '{1}'.", _
            callingDomainName, Thread.GetDomain().FriendlyName)
    End Sub
End Class

'This code produces output similar to the following:
' 
' AppDomainX.exe
' AppDomainX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
' AppName=, AppBase=C:\AppDomain\bin, ConfigFile=C:\AppDomain\bin\AppDomainX.exe.config
' Calling from 'AppDomainX.exe' to 'AD #2'.
' Failed call; this is expected.
using System;
using System.Reflection;
using System.Threading;

class Module1
{
    public static void Main()
    {
        // Get and display the friendly name of the default AppDomain.
        string callingDomainName = Thread.GetDomain().FriendlyName;
        Console.WriteLine(callingDomainName);

        // Get and display the full name of the EXE assembly.
        string exeAssembly = Assembly.GetEntryAssembly().FullName;
        Console.WriteLine(exeAssembly);

        // Construct and initialize settings for a second AppDomain.
        AppDomainSetup ads = new AppDomainSetup();
        ads.ApplicationBase = 
            "file:///" + System.Environment.CurrentDirectory;
        ads.DisallowBindingRedirects = false;
        ads.DisallowCodeDownload = true;
        ads.ConfigurationFile = 
            AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

        // Create the second AppDomain.
        AppDomain ad2 = AppDomain.CreateDomain("AD #2", null, ads);

        // Create an instance of MarshalbyRefType in the second AppDomain. 
        // A proxy to the object is returned.
        MarshalByRefType mbrt = 
            (MarshalByRefType) ad2.CreateInstanceAndUnwrap(
                exeAssembly, 
                typeof(MarshalByRefType).FullName
            );

        // Call a method on the object via the proxy, passing the 
        // default AppDomain's friendly name in as a parameter.
        mbrt.SomeMethod(callingDomainName);

        // Unload the second AppDomain. This deletes its object and 
        // invalidates the proxy object.
        AppDomain.Unload(ad2);
        try
        {
            // Call the method again. Note that this time it fails 
            // because the second AppDomain was unloaded.
            mbrt.SomeMethod(callingDomainName);
            Console.WriteLine("Sucessful call.");
        }
        catch(AppDomainUnloadedException)
        {
            Console.WriteLine("Failed call; this is expected.");
        }
    }
}

// Because this class is derived from MarshalByRefObject, a proxy 
// to a MarshalByRefType object can be returned across an AppDomain 
// boundary.
public class MarshalByRefType : MarshalByRefObject
{
    //  Call this method via a proxy.
    public void SomeMethod(string callingDomainName)
    {
        // Get this AppDomain's settings and display some of them.
        AppDomainSetup ads = AppDomain.CurrentDomain.SetupInformation;
        Console.WriteLine("AppName={0}, AppBase={1}, ConfigFile={2}", 
            ads.ApplicationName, 
            ads.ApplicationBase, 
            ads.ConfigurationFile
        );

        // Display the name of the calling AppDomain and the name 
        // of the second domain.
        // NOTE: The application's thread has transitioned between 
        // AppDomains.
        Console.WriteLine("Calling from '{0}' to '{1}'.", 
            callingDomainName, 
            Thread.GetDomain().FriendlyName
        );
    }
}

/* This code produces output similar to the following: 

AppDomainX.exe
AppDomainX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
AppName=, AppBase=C:\AppDomain\bin, ConfigFile=C:\AppDomain\bin\AppDomainX.exe.config
Calling from 'AppDomainX.exe' to 'AD #2'.
Failed call; this is expected.
 */
using namespace System;
using namespace System::Reflection;
using namespace System::Threading;
using namespace System::Security::Policy;

// Because this class is derived from MarshalByRefObject, a proxy 
// to a MarshalByRefType object can be returned across an AppDomain 
// boundary.
ref class MarshalByRefType : MarshalByRefObject
{
public:
    //  Call this method via a proxy.
    void SomeMethod(String^ callingDomainName)
    {
        // Get this AppDomain's settings and display some of them.
        AppDomainSetup^ ads = AppDomain::CurrentDomain->SetupInformation;
        Console::WriteLine("AppName={0}, AppBase={1}, ConfigFile={2}", 
            ads->ApplicationName, 
            ads->ApplicationBase, 
            ads->ConfigurationFile
        );

        // Display the name of the calling AppDomain and the name 
        // of the second domain.
        // NOTE: The application's thread has transitioned between 
        // AppDomains.
        Console::WriteLine("Calling from '{0}' to '{1}'.", 
            callingDomainName, 
            Thread::GetDomain()->FriendlyName
        );
    };
};

void main()
{
    // Get and display the friendly name of the default AppDomain.
    String^ callingDomainName = Thread::GetDomain()->FriendlyName;
    Console::WriteLine(callingDomainName);

    // Get and display the full name of the EXE assembly.
    String^ exeAssembly = Assembly::GetEntryAssembly()->FullName;
    Console::WriteLine(exeAssembly);

    // Construct and initialize settings for a second AppDomain.
    AppDomainSetup^ ads = gcnew AppDomainSetup();
    ads->ApplicationBase = 
        "file:///" + System::Environment::CurrentDirectory;
    ads->DisallowBindingRedirects = false;
    ads->DisallowCodeDownload = true;
    ads->ConfigurationFile = 
        AppDomain::CurrentDomain->SetupInformation->ConfigurationFile;

    // Create the second AppDomain.
    AppDomain^ ad2 = AppDomain::CreateDomain("AD #2", 
        AppDomain::CurrentDomain->Evidence, ads);

    // Create an instance of MarshalbyRefType in the second AppDomain. 
    // A proxy to the object is returned.
    MarshalByRefType^ mbrt = 
        (MarshalByRefType^) ad2->CreateInstanceAndUnwrap(
            exeAssembly, 
            MarshalByRefType::typeid->FullName
        );

    // Call a method on the object via the proxy, passing the 
    // default AppDomain's friendly name in as a parameter.
    mbrt->SomeMethod(callingDomainName);

    // Unload the second AppDomain. This deletes its object and 
    // invalidates the proxy object.
    AppDomain::Unload(ad2);
    try
    {
        // Call the method again. Note that this time it fails 
        // because the second AppDomain was unloaded.
        mbrt->SomeMethod(callingDomainName);
        Console::WriteLine("Sucessful call.");
    }
    catch(AppDomainUnloadedException^)
    {
        Console::WriteLine("Failed call; this is expected.");
    }
}

/* This code produces output similar to the following: 

AppDomainX.exe
AppDomainX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
AppName=, AppBase=C:\AppDomain\bin, ConfigFile=C:\AppDomain\bin\AppDomainX.exe.config
Calling from 'AppDomainX.exe' to 'AD #2'.
Failed call; this is expected.
 */

继承层次结构

System.Object
   System.MarshalByRefObject
    System.AppDomain

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

AppDomain 成员
System 命名空间