This documentation is archived and is not being maintained.

AppDomain Class

Represents an application domain, which is an isolated environment where applications execute. This class cannot be inherited.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

[ComVisibleAttribute(true)]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
public sealed class AppDomain : MarshalByRefObject, 
	_AppDomain, IEvidenceFactory

The AppDomain type exposes the following members.

  NameDescription
Public propertyActivationContextGets the activation context for the current application domain.
Public propertyApplicationIdentityGets the identity of the application in the application domain.
Public propertyApplicationTrustGets information describing permissions granted to an application and whether the application has a trust level that allows it to run.
Public propertyBaseDirectoryGets the base directory that the assembly resolver uses to probe for assemblies.
Public propertyStatic memberSupported by the XNA FrameworkCurrentDomainGets the current application domain for the current Thread.
Public propertyDomainManagerGets the domain manager that was provided by the host when the application domain was initialized.
Public propertyDynamicDirectoryGets the directory that the assembly resolver uses to probe for dynamically created assemblies.
Public propertyEvidenceGets the Evidence associated with this application domain.
Public propertySupported by the XNA FrameworkFriendlyNameGets the friendly name of this application domain.
Public propertyIdGets an integer that uniquely identifies the application domain within the process.
Public propertyIsFullyTrustedGets a value that indicates whether assemblies that are loaded into the current application domain execute with full trust.
Public propertyIsHomogenousGets a value that indicates whether the current application domain has a set of permissions that is granted to all assemblies that are loaded into the application domain.
Public propertyStatic memberMonitoringIsEnabledGets or sets a value that indicates whether CPU and memory monitoring of application domains is enabled for the current process. Once monitoring is enabled for a process, it cannot be disabled.
Public propertyMonitoringSurvivedMemorySizeGets the number of bytes that survived the last full, blocking collection and that are known to be referenced by the current application domain.
Public propertyStatic memberMonitoringSurvivedProcessMemorySizeGets the total bytes that survived from the last full, blocking collection for all application domains in the process.
Public propertyMonitoringTotalAllocatedMemorySizeGets the total size, in bytes, of all memory allocations that have been made by the application domain since it was created, without subtracting memory that has been collected.
Public propertyMonitoringTotalProcessorTimeGets the total processor time that has been used by all threads while executing in the current application domain, since the process started.
Public propertyPermissionSetGets the permission set of a sandboxed application domain.
Public propertyRelativeSearchPathGets the path under the base directory where the assembly resolver should probe for private assemblies.
Public propertySetupInformationGets the application domain configuration information for this instance.
Public propertyShadowCopyFilesGets an indication whether the application domain is configured to shadow copy files.
Top

  NameDescription
Public methodAppendPrivatePath Obsolete. Appends the specified directory name to the private path list.
Public methodApplyPolicyReturns the assembly display name after policy has been applied.
Public methodClearPrivatePath Obsolete. Resets the path that specifies the location of private assemblies to the empty string ("").
Public methodClearShadowCopyPath Obsolete. Resets the list of directories containing shadow copied assemblies to the empty string ("").
Public methodCreateComInstanceFrom(String, String)Creates a new instance of a specified COM type. Parameters specify the name of a file that contains an assembly containing the type and the name of the type.
Public methodCreateComInstanceFrom(String, String, Byte[], AssemblyHashAlgorithm)Creates a new instance of a specified COM type. Parameters specify the name of a file that contains an assembly containing the type and the name of the type.
Public methodStatic memberSupported by the XNA FrameworkCreateDomain(String)Creates a new application domain with the specified name.
Public methodStatic memberSupported by the XNA FrameworkCreateDomain(String, Evidence)Creates a new application domain with the given name using the supplied evidence.
Public methodStatic memberCreateDomain(String, Evidence, AppDomainSetup)Creates a new application domain using the specified name, evidence, and application domain setup information.
Public methodStatic memberCreateDomain(String, Evidence, AppDomainSetup, PermissionSet, StrongName[])Creates a new application domain using the specified name, evidence, application domain setup information, default permission set, and array of fully trusted assemblies.
Public methodStatic memberCreateDomain(String, Evidence, String, String, Boolean)Creates a new application domain with the given name, using evidence, application base path, relative search path, and a parameter that specifies whether a shadow copy of an assembly is to be loaded into the application domain.
Public methodStatic memberCreateDomain(String, Evidence, String, String, Boolean, AppDomainInitializer, String[])Creates a new application domain with the given name, using evidence, application base path, relative search path, and a parameter that specifies whether a shadow copy of an assembly is to be loaded into the application domain. Specifies a callback method that is invoked when the application domain is initialized, and an array of string arguments to pass the callback method.
Public methodCreateInstance(String, String)Creates a new instance of the specified type defined in the specified assembly.
Public methodCreateInstance(String, String, Object[])Creates a new instance of the specified type defined in the specified assembly. A parameter specifies an array of activation attributes.
Public methodCreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])Creates a new instance of the specified type defined in the specified assembly. Parameters specify a binder, binding flags, constructor arguments, culture-specific information used to interpret arguments, and optional activation attributes.
Public methodCreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) Obsolete. Creates a new instance of the specified type defined in the specified assembly. Parameters specify a binder, binding flags, constructor arguments, culture-specific information used to interpret arguments, activation attributes, and authorization to create the type.
Public methodCreateInstanceAndUnwrap(String, String)Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, and the name of the type.
Public methodCreateInstanceAndUnwrap(String, String, Object[])Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, the name of the type, and an array of activation attributes.
Public methodCreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])Creates a new instance of the specified type defined in the specified assembly, specifying whether the case of the type name is ignored; the binding attributes and the binder that are used to select the type to be created; the arguments of the constructor; the culture; and the activation attributes.
Public methodCreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) Obsolete. Creates a new instance of the specified type. Parameters specify the name of the type, and how it is found and created.
Public methodCreateInstanceFrom(String, String)Creates a new instance of the specified type defined in the specified assembly file.
Public methodCreateInstanceFrom(String, String, Object[])Creates a new instance of the specified type defined in the specified assembly file.
Public methodCreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])Creates a new instance of the specified type defined in the specified assembly file.
Public methodCreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) Obsolete. Creates a new instance of the specified type defined in the specified assembly file.
Public methodCreateInstanceFromAndUnwrap(String, String)Creates a new instance of the specified type defined in the specified assembly file.
Public methodCreateInstanceFromAndUnwrap(String, String, Object[])Creates a new instance of the specified type defined in the specified assembly file.
Public methodCreateInstanceFromAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])Creates a new instance of the specified type defined in the specified assembly file, specifying whether the case of the type name is ignored; the binding attributes and the binder that are used to select the type to be created; the arguments of the constructor; the culture; and the activation attributes.
Public methodCreateInstanceFromAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) Obsolete. Creates a new instance of the specified type defined in the specified assembly file.
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)Defines a dynamic assembly with the specified name and access mode.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>)Defines a dynamic assembly with the specified name, access mode, and custom attributes.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, Evidence) Obsolete. Defines a dynamic assembly using the specified name, access mode, and evidence.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String)Defines a dynamic assembly using the specified name, access mode, and storage directory.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>, SecurityContextSource)Defines a dynamic assembly with the specified name, access mode, and custom attributes, and using the specified source for its security context.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence) Obsolete. Defines a dynamic assembly using the specified name, access mode, storage directory, and evidence.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, PermissionSet, PermissionSet, PermissionSet) Obsolete. Defines a dynamic assembly using the specified name, access mode, and permission requests.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Boolean, IEnumerable<CustomAttributeBuilder>)Defines a dynamic assembly using the specified name, access mode, storage directory, and synchronization option.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, Evidence, PermissionSet, PermissionSet, PermissionSet) Obsolete. Defines a dynamic assembly using the specified name, access mode, evidence, and permission requests.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, PermissionSet, PermissionSet, PermissionSet) Obsolete. Defines a dynamic assembly using the specified name, access mode, storage directory, and permission requests.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet) Obsolete. Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, and permission requests.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet, Boolean) Obsolete. Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, permission requests, and synchronization option.
Public methodDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet, Boolean, IEnumerable<CustomAttributeBuilder>) Obsolete. Defines a dynamic assembly with the specified name, access mode, storage directory, evidence, permission requests, synchronization option, and custom attributes.
Public methodDoCallBackExecutes the code in another application domain that is identified by the specified delegate.
Public methodSupported by the XNA FrameworkEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkExecuteAssembly(String)Executes the assembly contained in the specified file.
Public methodExecuteAssembly(String, Evidence) Obsolete. Executes the assembly contained in the specified file, using the specified evidence.
Public methodExecuteAssembly(String, String[])Executes the assembly contained in the specified file, using the specified arguments.
Public methodSupported by the XNA FrameworkExecuteAssembly(String, Evidence, String[]) Obsolete. Executes the assembly contained in the specified file, using the specified evidence and arguments.
Public methodExecuteAssembly(String, String[], Byte[], AssemblyHashAlgorithm)Executes the assembly contained in the specified file, using the specified arguments, hash value, and hash algorithm.
Public methodExecuteAssembly(String, Evidence, String[], Byte[], AssemblyHashAlgorithm) Obsolete. Executes the assembly contained in the specified file, using the specified evidence, arguments, hash value, and hash algorithm.
Public methodExecuteAssemblyByName(String)Executes an assembly given its display name.
Public methodExecuteAssemblyByName(AssemblyName, String[])Executes the assembly given an AssemblyName, using the specified arguments.
Public methodExecuteAssemblyByName(String, Evidence) Obsolete. Executes an assembly given its display name, using the specified evidence.
Public methodExecuteAssemblyByName(String, String[])Executes the assembly given its display name, using the specified arguments.
Public methodExecuteAssemblyByName(AssemblyName, Evidence, String[]) Obsolete. Executes the assembly given an AssemblyName, using the specified evidence and arguments.
Public methodExecuteAssemblyByName(String, Evidence, String[]) Obsolete. Executes the assembly given its display name, using the specified evidence and arguments.
Protected methodSupported by the XNA FrameworkFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetAssembliesGets the assemblies that have been loaded into the execution context of this application domain.
Public methodStatic memberGetCurrentThreadId Obsolete. Gets the current thread identifier.
Public methodGetDataGets the value stored in the current application domain for the specified name.
Public methodSupported by the XNA FrameworkGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodSupported by the XNA FrameworkGetTypeGets the type of the current instance.

In XNA Framework 3.0, this member is inherited from Object.GetType().
Public methodInitializeLifetimeServiceGives the AppDomain an infinite lifetime by preventing a lease from being created. (Overrides MarshalByRefObject.InitializeLifetimeService().)
Public methodIsCompatibilitySwitchSetGets a nullable Boolean value that indicates whether any compatibility switches are set, and if so, whether the specified compatibility switch is set.
Public methodIsDefaultAppDomainReturns a value that indicates whether the application domain is the default application domain for the process.
Public methodIsFinalizingForUnloadIndicates whether this application domain is unloading, and the objects it contains are being finalized by the common language runtime.
Public methodLoad(AssemblyName)Loads an Assembly given its AssemblyName.
Public methodLoad(Byte[])Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly.
Public methodLoad(String)Loads an Assembly given its display name.
Public methodLoad(AssemblyName, Evidence) Obsolete. Loads an Assembly given its AssemblyName.
Public methodLoad(Byte[], Byte[])Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded.
Public methodLoad(String, Evidence) Obsolete. Loads an Assembly given its display name.
Public methodLoad(Byte[], Byte[], Evidence) Obsolete. Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded.
Protected methodSupported by the XNA FrameworkMemberwiseClone()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public methodReflectionOnlyGetAssembliesReturns the assemblies that have been loaded into the reflection-only context of the application domain.
Public methodSetAppDomainPolicy Obsolete. Establishes the security policy level for this application domain.
Public methodSetCachePath Obsolete. Establishes the specified directory path as the location where assemblies are shadow copied.
Public methodSetData(String, Object)Assigns the specified value to the specified application domain property.
Public methodSetData(String, Object, IPermission)Assigns the specified value to the specified application domain property, with a specified permission to demand of the caller when the property is retrieved.
Public methodSetDynamicBase Obsolete. Establishes the specified directory path as the base directory for subdirectories where dynamically generated files are stored and accessed.
Public methodSetPrincipalPolicySpecifies how principal and identity objects should be attached to a thread if the thread attempts to bind to a principal while executing in this application domain.
Public methodSetShadowCopyFiles Obsolete. Turns on shadow copying.
Public methodSetShadowCopyPath Obsolete. Establishes the specified directory path as the location of assemblies to be shadow copied.
Public methodSetThreadPrincipalSets the default principal object to be attached to threads if they attempt to bind to a principal while executing in this application domain.
Public methodSupported by the XNA FrameworkToStringObtains a string representation that includes the friendly name of the application domain and any context policies. (Overrides Object.ToString().)
Public methodStatic memberSupported by the XNA FrameworkUnloadUnloads the specified application domain.
Top

  NameDescription
Public eventAssemblyLoadOccurs when an assembly is loaded.
Public eventAssemblyResolveOccurs when the resolution of an assembly fails.
Public eventDomainUnloadOccurs when an AppDomain is about to be unloaded.
Public eventFirstChanceExceptionOccurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain.
Public eventProcessExitOccurs when the default application domain's parent process exits.
Public eventReflectionOnlyAssemblyResolveOccurs when the resolution of an assembly fails in the reflection-only context.
Public eventResourceResolveOccurs when the resolution of a resource fails because the resource is not a valid linked or embedded resource in the assembly.
Public eventTypeResolveOccurs when the resolution of a type fails.
Public eventSupported by the XNA FrameworkUnhandledExceptionOccurs when an exception is not caught.
Top

  NameDescription
Explicit interface implemetationPrivate method_AppDomain.GetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers.
Explicit interface implemetationPrivate method_AppDomain.GetTypeInfoRetrieves the type information for an object, which can then be used to get the type information for an interface.
Explicit interface implemetationPrivate method_AppDomain.GetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1).
Explicit interface implemetationPrivate method_AppDomain.InvokeProvides access to properties and methods exposed by an object.
Top

Application domains, which are represented by AppDomain objects, help provide isolation, unloading, and security boundaries for executing managed code.

  • Use application domains to isolate tasks that might bring down a process. If the state of the AppDomain that's executing a task becomes unstable, the AppDomain can be unloaded without affecting the process. This is important when a process must run for long periods without restarting. You can also use application domains to isolate tasks that should not share data.

  • If an assembly is loaded into the default application domain, it cannot be unloaded from memory while the process is running. However, if you open a second application domain to load and execute the assembly, the assembly is unloaded when that application domain is unloaded. Use this technique to minimize the working set of long-running processes that occasionally use large DLLs.

Multiple application domains can run in a single process; however, there is not a one-to-one correlation between application domains and threads. Several threads can belong to a single application domain, and while a given thread is not confined to a single application domain, at any given time, a thread executes in a single application domain.

Application domains are created using the CreateDomain method. AppDomain instances are used to load and execute assemblies (Assembly). When an AppDomain is no longer in use, it can be unloaded.

The AppDomain class implements a set of events that enable applications to respond when an assembly is loaded, when an application domain will be unloaded, or when an unhandled exception is thrown.

For more information on using application domains, see Application Domains.

This class implements the MarshalByRefObject, _AppDomain, and IEvidenceFactory interfaces.

You should never create a remotable wrapper for an AppDomain object. Doing so could publish a remote reference to that AppDomain, exposing methods such as CreateInstance to remote access and effectively destroying code access security for that AppDomain. Malicious clients connecting to the remoted AppDomain could obtain access to any resource the AppDomain itself has access to. Do not create remotable wrappers for any type that extends MarshalByRefObject and that implements methods that could be used by malicious clients to bypass the security system.

Caution noteCaution

The default value for the AppDomainSetup.DisallowCodeDownload property is false. This setting is unsafe for services. To prevent services from downloading partially trusted code, set this property to true.

TopicLocation
How to: Configure an Application Domain.NET Framework: Programming Fundamentals
How to: Load Assemblies into an Application Domain.NET Framework: Programming Fundamentals
How to: Create an Application Domain.NET Framework: Programming Fundamentals
How to: Unload an Application Domain.NET Framework: Programming Fundamentals
How to: Configure an Application Domain.NET Framework: Programming Fundamentals
How to: Load Assemblies into an Application Domain.NET Framework: Programming Fundamentals
How to: Create an Application Domain.NET Framework: Programming Fundamentals
How to: Unload an Application Domain.NET Framework: Programming Fundamentals
How to: Configure an Application Domain

This example shows how to create a new AppDomain, instantiate a type in that new AppDomain, and communicate with that type’s object. In addition, this example shows how to unload the AppDomain causing the object to be garbage collected.


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 = 
            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.
 */


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show: