System


Riferimento a .NET Framework
Classe AppDomain

Rappresenta un dominio applicazione, ovvero un ambiente isolato nel quale vengono eseguite le applicazioni. Questa classe non può essere ereditata.

Spazio dei nomi: System
Assembly: mscorlib (in mscorlib.dll)

Sintassi

Visual Basic - (Dichiarazione)
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
<ComVisibleAttribute(True)> _
Public NotInheritable Class AppDomain
    Inherits MarshalByRefObject
    Implements _AppDomain, IEvidenceFactory
Visual Basic (Utilizzo)
Dim instance As AppDomain
C#
[ClassInterfaceAttribute(ClassInterfaceType.None)] 
[ComVisibleAttribute(true)] 
public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory
C++
[ClassInterfaceAttribute(ClassInterfaceType::None)] 
[ComVisibleAttribute(true)] 
public ref class AppDomain sealed : public MarshalByRefObject, _AppDomain, IEvidenceFactory
J#
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.None) */ 
/** @attribute ComVisibleAttribute(true) */ 
public final class AppDomain extends MarshalByRefObject implements _AppDomain, IEvidenceFactory
JScript
ClassInterfaceAttribute(ClassInterfaceType.None) 
ComVisibleAttribute(true) 
public final class AppDomain extends MarshalByRefObject implements _AppDomain, IEvidenceFactory
Note

I domini applicazioni, rappresentati da oggetti AppDomain, forniscono limiti di protezione, scaricamento e isolamento per l'esecuzione del codice gestito.

  • Utilizzare i domini applicazioni per isolare le attività che potrebbero interferire con un processo. Se lo stato del dominio applicazione rappresentato dall'oggetto AppDomain che esegue un'attività diventa instabile, è possibile scaricarlo senza interferire con il processo. Tale operazione è utile quando è necessario eseguire un processo per lunghi periodi di tempo senza riavviarlo. I domini applicazioni possono anche essere utilizzati per isolare le attività i cui dati non devono essere condivisi.

  • Se un assembly viene caricato nel dominio applicazione predefinito, non è possibile scaricarlo dalla memoria mentre il processo è in esecuzione. Tuttavia, se si apre un secondo dominio applicazione per caricare ed eseguire l'assembly, quest'ultimo viene scaricato quando viene caricato il secondo dominio applicazione. Utilizzare questa tecnica per ridurre il working set di processi a esecuzione prolungata che talvolta utilizzano DLL di grandi dimensioni.

I domini applicazioni multipli possono essere eseguiti in un solo processo. Non sussiste, comunque, alcuna relazione biunivoca tra domini applicazioni e thread. Ad un solo dominio applicazione possono appartenere più thread. Sebbene un determinato thread non sia confinato a un unico dominio applicazione, un thread può essere eseguito in un singolo dominio applicazione per volta.

I domini applicazioni vengono creati utilizzando il metodo CreateDomain. Le istanze di AppDomain vengono utilizzate per caricare ed eseguire assembly (Assembly). Quando un oggetto AppDomain non è più in uso, può essere scaricato.

La classe AppDomain implementa un insieme di eventi che consentono alle applicazioni di rispondere quando viene caricato un assembly, viene scaricato un dominio applicazione o viene generata un'eccezione non gestita.

Per ulteriori informazioni sull'utilizzo dei domini applicazioni, vedere Domini applicazione.

Questa classe implementa le interfacce MarshalByRefObject, _AppDomain e IEvidenceFactory.

Non creare mai un wrapper remotizzabile per un oggetto AppDomain. Questa operazione può infatti indurre la pubblicazione di un riferimento remoto all'oggetto AppDomain, esponendo metodi quali CreateInstance all'accesso remoto ed eliminando di fatto la protezione dall'accesso di codice dell'oggetto AppDomain. Client non autorizzati potrebbero connettersi all'oggetto AppDomain remoto e ottenere così accesso a qualsiasi risorsa a cui lo stesso oggetto AppDomain abbia accesso. Non creare wrapper remotizzabili per tipi che estendono l'oggetto MarshalByRefObject e che implementano metodi che potrebbero essere utilizzati da client non autorizzati per eludere il sistema di protezione.

Nota di avvisoAttenzione

Il valore predefinito per la proprietà AppDomainSetup.DisallowCodeDownload è false. Questa impostazione non è affidabile per la protezione dei servizi. Per impedire il download di codice parzialmente attendibile da parte di servizi, impostare la proprietà su true.

Nota sulla piattaforma Windows Mobile per Pocket PC, Windows Mobile per Smartphone, Windows CE: Il caricamento di assembly in un'area di codice indipendente dal dominio per renderli utilizzabili in più domini applicazione non è supportato.

TopicLocation
Procedura: caricare assembly in un dominio applicazione.NET Framework: Nozioni fondamentali sulla programmazione
Procedura: caricare assembly in un dominio applicazione.NET Framework: Nozioni fondamentali sulla programmazione
Procedura: configurare un dominio applicazione.NET Framework: Nozioni fondamentali sulla programmazione
Procedura: configurare un dominio applicazione.NET Framework: Nozioni fondamentali sulla programmazione
Procedura: creare un dominio applicazione.NET Framework: Nozioni fondamentali sulla programmazione
Procedura: creare un dominio applicazione.NET Framework: Nozioni fondamentali sulla programmazione
Procedura: scaricare un dominio applicazione.NET Framework: Nozioni fondamentali sulla programmazione
Procedura: scaricare un dominio applicazione.NET Framework: Nozioni fondamentali sulla programmazione
Esempio

Nell'esempio riportato di seguito viene illustrato come creare un nuovo oggetto AppDomain, istanziarvi un tipo e quindi comunicare con l'oggetto di tale tipo. Inoltre, nell'esempio è illustrato come scaricare l'oggetto AppDomain facendo in modo che l'oggetto venga raccolto nel Garbage Collector.

Visual Basic
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.
C#
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.
 */
C++
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.
 */
Gerarchia di ereditarietà

System.Object
   System.MarshalByRefObject
    System.AppDomain
Codice thread safe

I membri statici pubblici (Shared in Visual Basic) di questo tipo sono validi per le operazioni multithreading. I membri di istanza non sono garantiti come thread safe.
Piattaforme

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

.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema.

Informazioni sulla versione

.NET Framework

Supportato in: 2.0 1.1 1.0

.NET Compact Framework

Supportato in: 2.0 1.0
Vedere anche

Tag :


Page view tracker