AppDomain
AppDomain
AppDomain
AppDomain
Class
Definition
Represents an application domain, which is an isolated environment where applications execute. This class cannot be inherited.
public ref class AppDomain sealed : MarshalByRefObject, _AppDomain, System::Security::IEvidenceFactory
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AppDomain : MarshalByRefObject, _AppDomain, System.Security.IEvidenceFactory
type AppDomain = class
inherit MarshalByRefObject
interface _AppDomain
interface IEvidenceFactory
Public NotInheritable Class AppDomain
Inherits MarshalByRefObject
Implements _AppDomain, IEvidenceFactory
- Inheritance
-
AppDomainAppDomainAppDomainAppDomain
- Attributes
- Implements
Examples
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 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 = AppDomain::CurrentDomain->BaseDirectory;
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.
*/
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 = AppDomain.CurrentDomain.BaseDirectory;
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.
*/
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 = AppDomain.CurrentDomain.BaseDirectory
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.
Remarks
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.
Note
On .NET Core, the AppDomain implementation is limited by design and does not provide isolation, unloading, or security boundaries. For .NET Core, there is exactly one AppDomain. Isolation and unloading are provided through AssemblyLoadContext. Security boundaries should be provided by process boundaries and appropriate remoting techniques.
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
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
.
Properties
ActivationContext ActivationContext ActivationContext ActivationContext |
Gets the activation context for the current application domain. |
ApplicationIdentity ApplicationIdentity ApplicationIdentity ApplicationIdentity |
Gets the identity of the application in the application domain. |
ApplicationTrust ApplicationTrust ApplicationTrust ApplicationTrust |
Gets information describing permissions granted to an application and whether the application has a trust level that allows it to run. |
BaseDirectory BaseDirectory BaseDirectory BaseDirectory |
Gets the base directory that the assembly resolver uses to probe for assemblies. |
CurrentDomain CurrentDomain CurrentDomain CurrentDomain |
Gets the current application domain for the current Thread. |
DomainManager DomainManager DomainManager DomainManager |
Gets the domain manager that was provided by the host when the application domain was initialized. |
DynamicDirectory DynamicDirectory DynamicDirectory DynamicDirectory |
Gets the directory that the assembly resolver uses to probe for dynamically created assemblies. |
Evidence Evidence Evidence Evidence |
Gets the Evidence associated with this application domain. |
FriendlyName FriendlyName FriendlyName FriendlyName |
Gets the friendly name of this application domain. |
Id Id Id Id |
Gets an integer that uniquely identifies the application domain within the process. |
IsFullyTrusted IsFullyTrusted IsFullyTrusted IsFullyTrusted |
Gets a value that indicates whether assemblies that are loaded into the current application domain execute with full trust. |
IsHomogenous IsHomogenous IsHomogenous IsHomogenous |
Gets 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. |
MonitoringIsEnabled MonitoringIsEnabled MonitoringIsEnabled MonitoringIsEnabled |
Gets 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. |
MonitoringSurvivedMemorySize MonitoringSurvivedMemorySize MonitoringSurvivedMemorySize MonitoringSurvivedMemorySize |
Gets the number of bytes that survived the last collection and that are known to be referenced by the current application domain. |
MonitoringSurvivedProcessMemorySize MonitoringSurvivedProcessMemorySize MonitoringSurvivedProcessMemorySize MonitoringSurvivedProcessMemorySize |
Gets the total bytes that survived from the last collection for all application domains in the process. |
MonitoringTotalAllocatedMemorySize MonitoringTotalAllocatedMemorySize MonitoringTotalAllocatedMemorySize MonitoringTotalAllocatedMemorySize |
Gets 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. |
MonitoringTotalProcessorTime MonitoringTotalProcessorTime MonitoringTotalProcessorTime MonitoringTotalProcessorTime |
Gets the total processor time that has been used by all threads while executing in the current application domain, since the process started. |
PermissionSet PermissionSet PermissionSet PermissionSet |
Gets the permission set of a sandboxed application domain. |
RelativeSearchPath RelativeSearchPath RelativeSearchPath RelativeSearchPath |
Gets the path under the base directory where the assembly resolver should probe for private assemblies. |
SetupInformation SetupInformation SetupInformation SetupInformation |
Gets the application domain configuration information for this instance. |
ShadowCopyFiles ShadowCopyFiles ShadowCopyFiles ShadowCopyFiles |
Gets an indication whether the application domain is configured to shadow copy files. |
Methods
Events
AssemblyLoad AssemblyLoad AssemblyLoad AssemblyLoad |
Occurs when an assembly is loaded. |
AssemblyResolve AssemblyResolve AssemblyResolve AssemblyResolve |
Occurs when the resolution of an assembly fails. |
DomainUnload DomainUnload DomainUnload DomainUnload |
Occurs when an AppDomain is about to be unloaded. |
FirstChanceException FirstChanceException FirstChanceException FirstChanceException |
Occurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain. |
ProcessExit ProcessExit ProcessExit ProcessExit |
Occurs when the default application domain's parent process exits. |
ReflectionOnlyAssemblyResolve ReflectionOnlyAssemblyResolve ReflectionOnlyAssemblyResolve ReflectionOnlyAssemblyResolve |
Occurs when the resolution of an assembly fails in the reflection-only context. |
ResourceResolve ResourceResolve ResourceResolve ResourceResolve |
Occurs when the resolution of a resource fails because the resource is not a valid linked or embedded resource in the assembly. |
TypeResolve TypeResolve TypeResolve TypeResolve |
Occurs when the resolution of a type fails. |
UnhandledException UnhandledException UnhandledException UnhandledException |
Occurs when an exception is not caught. |
Explicit Interface Implementations
Applies to
See also
Feedback
We’d love to hear your thoughts. Choose the type you’d like to provide:
Our feedback system is built on GitHub Issues. Read more on our blog.
Loading feedback...