AppDomainUnloadedException Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
A exceção que é lançada quando se tenta aceder a um domínio de aplicação descarregado.
public ref class AppDomainUnloadedException : SystemException
public class AppDomainUnloadedException : SystemException
[System.Serializable]
public class AppDomainUnloadedException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class AppDomainUnloadedException : SystemException
type AppDomainUnloadedException = class
inherit SystemException
[<System.Serializable>]
type AppDomainUnloadedException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
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 an AppDomainUnloadedException em vários threads, e o segundo mostra o descarregamento elementar do domínio da aplicação.
Exemplo 1
O exemplo de código seguinte define uma classe TestClass que pode ser escalada através dos limites do domínio da aplicação e uma classe Example contendo um método static (Shared em Visual Basic) ThreadProc. O ThreadProc método cria um domínio de aplicação, cria um TestClass objeto no domínio e chama um método de TestClass que descarrega o domínio em execução, causando um AppDomainUnloadedException.
O TestClass método é executado sem tratamento de exceções a partir de uma ThreadPool thread e de uma thread comum, demonstrando que a exceção não tratada termina a tarefa ou thread, mas não a aplicação. É então executado com e sem exceção a partir da thread principal da aplicação, demonstrando que termina a aplicação se não for tratada.
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 seguinte cria e descarrega um domínio de aplicação, e demonstra que um AppDomainUnloadedException é lançado numa tentativa subsequente de aceder ao 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
Observações
Na versão 2.0 do .NET Framework, um AppDomainUnloadedException que não é tratado no código do utilizador tem o seguinte efeito:
Se um thread foi iniciado em código gerido, é terminado. A exceção não tratada não pode terminar a aplicação.
Se uma tarefa estiver a ser executada num ThreadPool thread, é terminado e o thread é devolvido ao pool de threads. A exceção não tratada não pode terminar a aplicação.
Se um thread começou em código não gerido, como o thread principal da aplicação, é terminado. A exceção não tratada é permitida prosseguir, e o sistema operativo termina a aplicação.
AppDomainUnloadedException utiliza o COR_E_APPDOMAINUNLOADED HRESULT, que tem o valor 0x80131014.
Para obter uma lista dos valores iniciais de propriedade de uma instância de AppDomainUnloadedException, consulte os construtores de AppDomainUnloadedException.
Construtores
| Name | Description |
|---|---|
| AppDomainUnloadedException() |
Inicializa uma nova instância da AppDomainUnloadedException classe. |
| AppDomainUnloadedException(SerializationInfo, StreamingContext) |
Obsoleto.
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 AppDomainUnloadedException classe com uma mensagem de erro especificada. |
Propriedades
| Name | Description |
|---|---|
| Data |
Obtém uma coleção de pares chave/valor que fornecem informação adicional definida pelo utilizador sobre a exceção. (Herdado de Exception) |
| HelpLink |
Obtém ou define um link para o ficheiro de ajuda associado a esta exceção. (Herdado de Exception) |
| HResult |
Recebe 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 |
Recebe uma mensagem que descreve a exceção atual. (Herdado de Exception) |
| Source |
Obtém ou define o nome do aplicativo ou o objeto que causa o erro. (Herdado de Exception) |
| StackTrace |
Obtém uma representação string dos frames imediatos na stack de chamadas. (Herdado de Exception) |
| TargetSite |
Obtém o método que lança a exceção atual. (Herdado de Exception) |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetBaseException() |
Quando sobrescrito numa classe derivada, devolve o Exception que é a causa raiz de uma ou mais exceções subsequentes. (Herdado de Exception) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Obsoleto.
Quando sobreposto numa classe derivada, define a SerializationInfo informação com sobre a exceção. (Herdado de Exception) |
| GetType() |
Obtém o tipo de execução da instância atual. (Herdado de Exception) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Cria e devolve uma representação string da exceção atual. (Herdado de Exception) |
evento
| Name | Description |
|---|---|
| SerializeObjectState |
Obsoleto.
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) |