AppDomainUnloadedException Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
A exceção gerada quando é feita uma tentativa de acessar um domínio de aplicativo descarregado.
public ref class AppDomainUnloadedException : SystemException
[System.Serializable]
public class AppDomainUnloadedException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class AppDomainUnloadedException : SystemException
public class AppDomainUnloadedException : SystemException
[<System.Serializable>]
type AppDomainUnloadedException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type AppDomainUnloadedException = class
inherit SystemException
type AppDomainUnloadedException = class
inherit SystemException
Public Class AppDomainUnloadedException
Inherits SystemException
- Herança
- Atributos
Exemplos
Esta seção contém dois exemplos de código. O primeiro exemplo demonstra os efeitos de um AppDomainUnloadedException em vários threads e o segundo mostra o descarregamento de domínio de aplicativo elementar.
Exemplo 1
O exemplo de código a seguir define uma classe TestClass que pode ser marshalada entre limites de domínio do aplicativo e uma classe Example que contém um método static (Shared no Visual Basic) ThreadProc. O ThreadProc método cria um domínio de aplicativo, cria um TestClass objeto no domínio e chama um método do TestClass qual descarrega o domínio em execução, causando um AppDomainUnloadedException.
O TestClass método é executado sem tratamento de exceção de um ThreadPool thread e de um thread comum, demonstrando que a exceção sem tratamento encerra a tarefa ou o thread, mas não o aplicativo. Em seguida, ele é executado com e sem tratamento de exceção do thread principal do aplicativo, demonstrando que ele encerra o aplicativo se não for tratado.
using System;
using System.Threading;
using System.Runtime.InteropServices;
public class Example
{
public static void Main()
{
// 1. Queue ThreadProc as a task for a ThreadPool thread.
ThreadPool.QueueUserWorkItem(ThreadProc, " from a ThreadPool thread");
Thread.Sleep(1000);
// 2. Execute ThreadProc on an ordinary thread.
Thread t = new Thread(ThreadProc);
t.Start(" from an ordinary thread");
t.Join();
// 3. Execute ThreadProc on the main thread, with
// exception handling.
try
{
ThreadProc(" from the main application thread (handled)");
}
catch (AppDomainUnloadedException adue)
{
Console.WriteLine("Main thread caught AppDomainUnloadedException: {0}", adue.Message);
}
// 4. Execute ThreadProc on the main thread without
// exception handling.
ThreadProc(" from the main application thread (unhandled)");
Console.WriteLine("Main: This message is never displayed.");
}
private static void ThreadProc(object state)
{
// Create an application domain, and create an instance
// of TestClass in the application domain. The first
// parameter of CreateInstanceAndUnwrap is the name of
// this executable. If you compile the example code using
// any name other than "Sample.exe", you must change the
// parameter appropriately.
AppDomain ad = AppDomain.CreateDomain("TestDomain");
TestClass tc = (TestClass)ad.CreateInstanceAndUnwrap("Sample", "TestClass");
// In the new application domain, execute a method that
// unloads the AppDomain. The unhandled exception this
// causes ends the current thread.
tc.UnloadCurrentDomain(state);
Console.WriteLine("ThreadProc: This message is never displayed.");
}
}
// TestClass derives from MarshalByRefObject, so it can be marshaled
// across application domain boundaries.
//
public class TestClass : MarshalByRefObject
{
public void UnloadCurrentDomain(object state)
{
Console.WriteLine("\nUnloading the current AppDomain{0}.", state);
// Unload the current application domain. This causes
// an AppDomainUnloadedException to be thrown.
//
AppDomain.Unload(AppDomain.CurrentDomain);
}
}
/* This code example produces output similar to the following:
Unloading the current AppDomain from a ThreadPool thread.
Unloading the current AppDomain from an ordinary thread.
Unloading the current AppDomain from the main application thread (handled).
Main thread caught AppDomainUnloadedException: The application domain in which the thread was running has been unloaded.
Unloading the current AppDomain from the main application thread (unhandled).
Unhandled Exception: System.AppDomainUnloadedException: The application domain in which the thread was running has been unloaded.
at TestClass.UnloadCurrentDomain(Object state)
at Example.ThreadProc(Object state)
at Example.Main()
*/
open System
open System.Threading
// TestClass derives from MarshalByRefObject, so it can be marshaled
// across application domain boundaries.
type TestClass() =
inherit MarshalByRefObject()
member _.UnloadCurrentDomain (state: obj) =
printfn $"\nUnloading the current AppDomain{state}."
// Unload the current application domain. This causes
// an AppDomainUnloadedException to be thrown.
//
AppDomain.Unload AppDomain.CurrentDomain
let threadProc (state: obj) =
// Create an application domain, and create an instance
// of TestClass in the application domain. The first
// parameter of CreateInstanceAndUnwrap is the name of
// this executable. If you compile the example code using
// any name other than "Sample.exe", you must change the
// parameter appropriately.
let ad = AppDomain.CreateDomain "TestDomain"
let tc = ad.CreateInstanceAndUnwrap("Sample", "TestClass") :?> TestClass
// In the new application domain, execute a method that
// unloads the AppDomain. The unhandled exception this
// causes ends the current thread.
tc.UnloadCurrentDomain state
printfn "ThreadProc: This message is never displayed."
// 1. Queue ThreadProc as a task for a ThreadPool thread.
ThreadPool.QueueUserWorkItem(threadProc, " from a ThreadPool thread") |> ignore
Thread.Sleep 1000
// 2. Execute ThreadProc on an ordinary thread.
let t = Thread(ParameterizedThreadStart threadProc)
t.Start " from an ordinary thread"
t.Join()
// 3. Execute ThreadProc on the main thread, with
// exception handling.
try
threadProc " from the main application thread (handled)"
with :? AppDomainUnloadedException as adue ->
printfn $"Main thread caught AppDomainUnloadedException: {adue.Message}"
// 4. Execute ThreadProc on the main thread without
// exception handling.
threadProc " from the main application thread (unhandled)"
printfn "Main: This message is never displayed."
(* This code example produces output similar to the following:
Unloading the current AppDomain from a ThreadPool thread.
Unloading the current AppDomain from an ordinary thread.
Unloading the current AppDomain from the main application thread (handled).
Main thread caught AppDomainUnloadedException: The application domain in which the thread was running has been unloaded.
Unloading the current AppDomain from the main application thread (unhandled).
Unhandled Exception: System.AppDomainUnloadedException: The application domain in which the thread was running has been unloaded.
at TestClass.UnloadCurrentDomain(Object state)
at Example.ThreadProc(Object state)
at Example.main()
*)
Imports System.Threading
Imports System.Runtime.InteropServices
Public Class Example
Public Shared Sub Main()
' 1. Queue ThreadProc as a task for a ThreadPool thread.
ThreadPool.QueueUserWorkItem(AddressOf ThreadProc, _
" from a ThreadPool thread")
Thread.Sleep(1000)
' 2. Execute ThreadProc on an ordinary thread.
Dim t As New Thread(AddressOf ThreadProc)
t.Start(" from an ordinary thread")
t.Join()
' 3. Execute ThreadProc on the main thread, with
' exception handling.
Try
ThreadProc(" from the main application thread (handled)")
Catch adue As AppDomainUnloadedException
Console.WriteLine("Main thread caught AppDomainUnloadedException: {0}", _
adue.Message)
End Try
' 4. Execute ThreadProc on the main thread without
' exception handling.
ThreadProc(" from the main application thread (unhandled)")
Console.WriteLine("Main: This message is never displayed.")
End Sub
Private Shared Sub ThreadProc(ByVal state As Object)
' Create an application domain, and create an instance
' of TestClass in the application domain. The first
' parameter of CreateInstanceAndUnwrap is the name of
' this executable. If you compile the example code using
' any name other than "Sample.exe", you must change the
' parameter appropriately.
Dim ad As AppDomain = AppDomain.CreateDomain("TestDomain")
Dim o As Object = ad.CreateInstanceAndUnwrap("Sample", "TestClass")
Dim tc As TestClass = CType(o, TestClass)
' In the new application domain, execute a method that
' unloads the AppDomain. The unhandled exception this
' causes ends the current thread.
tc.UnloadCurrentDomain(state)
Console.WriteLine("ThreadProc: This message is never displayed.")
End Sub
End Class
' TestClass derives from MarshalByRefObject, so it can be marshaled
' across application domain boundaries.
'
Public Class TestClass
Inherits MarshalByRefObject
Public Sub UnloadCurrentDomain(ByVal state As Object)
Console.WriteLine(vbLf & "Unloading the current AppDomain{0}.", state)
' Unload the current application domain. This causes
' an AppDomainUnloadedException to be thrown.
'
AppDomain.Unload(AppDomain.CurrentDomain)
End Sub
End Class
' This code example produces output similar to the following:
'
'Unloading the current AppDomain from a ThreadPool thread.
'
'Unloading the current AppDomain from an ordinary thread.
'
'Unloading the current AppDomain from the main application thread (handled).
'Main thread caught AppDomainUnloadedException: The application domain in which the thread was running has been unloaded.
'
'Unloading the current AppDomain from the main application thread (unhandled).
'
'Unhandled Exception: System.AppDomainUnloadedException: The application domain in which the thread was running has been unloaded.
' at TestClass.UnloadCurrentDomain(Object state)
' at Example.ThreadProc(Object state)
' at Example.Main()
'
Exemplo 2
O exemplo de código a seguir cria e descarrega um domínio de aplicativo e demonstra que um AppDomainUnloadedException é gerado em uma tentativa subsequente de acessar o domínio descarregado.
using namespace System;
using namespace System::Reflection;
using namespace System::Security::Policy;
//for evidence Object*
int 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: {0}", AppDomain::CurrentDomain->FriendlyName );
Console::WriteLine( "child domain: {0}", 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: {0}", domain->FriendlyName );
}
catch ( AppDomainUnloadedException^ /*e*/ )
{
Console::WriteLine( "The appdomain MyDomain does not exist." );
}
}
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.");
}
}
}
open System
//Create evidence for the new appdomain.
let adevidence = AppDomain.CurrentDomain.Evidence
// Create the new application domain.
let domain = AppDomain.CreateDomain("MyDomain", adevidence)
printfn $"Host domain: {AppDomain.CurrentDomain.FriendlyName}"
printfn $"child domain: {domain.FriendlyName}"
// Unload the application domain.
AppDomain.Unload domain
try
printfn ""
// Note that the following statement creates an exception because the domain no longer exists.
printfn $"child domain: {domain.FriendlyName}"
with :? AppDomainUnloadedException ->
printfn "The appdomain MyDomain does not exist."
Imports System.Reflection
Imports System.Security.Policy
Class ADUnload
Public Shared Sub Main()
'Create evidence for the new appdomain.
Dim adevidence As Evidence = AppDomain.CurrentDomain.Evidence
' Create the new application domain.
Dim domain As AppDomain = 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 e As AppDomainUnloadedException
Console.WriteLine("The appdomain MyDomain does not exist.")
End Try
End Sub
End Class
Comentários
No .NET Framework versão 2.0, um AppDomainUnloadedException que não é tratado no código do usuário tem o seguinte efeito:
Se um thread tiver sido iniciado no código gerenciado, ele será encerrado. A exceção sem tratamento não tem permissão para encerrar o aplicativo.
Se uma tarefa estiver sendo executada em um ThreadPool thread, ela será encerrada e o thread será retornado para o pool de threads. A exceção sem tratamento não tem permissão para encerrar o aplicativo.
Se um thread iniciado em código não gerenciado, como o thread do aplicativo principal, ele será encerrado. A exceção sem tratamento tem permissão para continuar e o sistema operacional encerra o aplicativo.
AppDomainUnloadedException usa o COR_E_APPDOMAINUNLOADED HRESULT, que tem o valor 0x80131014.
Para obter uma lista de valores de propriedade iniciais de uma instância de AppDomainUnloadedException, consulte os construtores de AppDomainUnloadedException.
Construtores
| Nome | Description |
|---|---|
| AppDomainUnloadedException() |
Inicializa uma nova instância da classe AppDomainUnloadedException. |
| AppDomainUnloadedException(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da AppDomainUnloadedException classe com dados serializados. |
| AppDomainUnloadedException(String, Exception) |
Inicializa uma nova instância da AppDomainUnloadedException classe com uma mensagem de erro especificada e uma referência à exceção interna que é a causa dessa exceção. |
| AppDomainUnloadedException(String) |
Inicializa uma nova instância da classe AppDomainUnloadedException com uma mensagem de erro especificada. |
Propriedades
| Nome | Description |
|---|---|
| Data |
Obtém uma coleção de pares chave/valor que fornecem informações adicionais definidas pelo usuário sobre a exceção. (Herdado de Exception) |
| HelpLink |
Obtém ou define um link para o arquivo de ajuda associado a essa exceção. (Herdado de Exception) |
| HResult |
Obtém ou define HRESULT, um valor numérico codificado atribuído a uma exceção específica. (Herdado de Exception) |
| InnerException |
Obtém a Exception instância que causou a exceção atual. (Herdado de Exception) |
| Message |
Obtém uma mensagem que descreve a exceção atual. (Herdado de Exception) |
| Source |
Obtém ou define o nome do aplicativo ou do objeto que causa o erro. (Herdado de Exception) |
| StackTrace |
Obtém uma representação de cadeia de caracteres dos quadros imediatos na pilha de chamadas. (Herdado de Exception) |
| TargetSite |
Obtém o método que gera a exceção atual. (Herdado de Exception) |
Métodos
| Nome | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetBaseException() |
Quando substituído em uma classe derivada, retorna a Exception causa raiz de uma ou mais exceções subsequentes. (Herdado de Exception) |
| GetHashCode() |
Serve como a função hash predefinida. (Herdado de Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Quando substituído em uma classe derivada, define o SerializationInfo com informações sobre a exceção. (Herdado de Exception) |
| GetType() |
Obtém o tipo de runtime da instância atual. (Herdado de Exception) |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| ToString() |
Cria e retorna uma representação de cadeia de caracteres da exceção atual. (Herdado de Exception) |
Eventos
| Nome | Description |
|---|---|
| SerializeObjectState |
Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção. (Herdado de Exception) |