AppDomain.FirstChanceException AppDomain.FirstChanceException AppDomain.FirstChanceException AppDomain.FirstChanceException Event

Definição

Ocorre quando uma exceção é lançada no código gerenciado, antes que o tempo de execução procure na pilha de chamadas um manipulador de exceção no domínio do aplicativo.Occurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain.

public:
 event EventHandler<System::Runtime::ExceptionServices::FirstChanceExceptionEventArgs ^> ^ FirstChanceException;
[add: System.Security.SecurityCritical]
[remove: System.Security.SecurityCritical]
public event EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException;
member this.FirstChanceException : EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> 
Public Custom Event FirstChanceException As EventHandler(Of FirstChanceExceptionEventArgs) 
Atributos

Exemplos

O exemplo a seguir cria uma série de domínios de AD0 aplicativo AD3chamados por meio Worker de, com um objeto em cada domínio de aplicativo.The following example creates a series of application domains named AD0 through AD3, with a Worker object in each application domain. Cada Worker objeto tem uma referência Worker ao objeto no próximo domínio do aplicativo, exceto para o Worker no último domínio do aplicativo.Each Worker object has a reference to the Worker object in the next application domain, except for the Worker in the last application domain. O FirstChanceException evento é tratado em todos os domínios de AD1aplicativo, exceto.The FirstChanceException event is handled in all application domains except AD1.

Observação

Além deste exemplo, que demonstra notificações de exceção de primeira chance em vários domínios de aplicativo, você pode encontrar casos de uso simples em como: Receber notificaçõesde exceção de primeira chance.In addition to this example, which demonstrates first-chance exception notifications in multiple application domains, you can find simple use cases in How to: Receive First-Chance Exception Notifications.

Quando os domínios de aplicativo tiverem sido criados, o domínio de aplicativo padrão TestException chamará o método para o primeiro domínio de aplicativo.When the application domains have been created, the default application domain calls the TestException method for the first application domain. Cada Worker objeto chama o TestException método para o próximo domínio de aplicativo, até que Worker o último lance uma exceção que seja manipulada ou não tratada.Each Worker object calls the TestException method for the next application domain, until the last Worker throws an exception that is either handled or unhandled. Assim, o thread atual passa por todos os domínios de aplicativo e TestException é adicionado à pilha em cada domínio de aplicativo.Thus, the current thread passes through all the application domains, and TestException is added to the stack in each application domain.

Quando o último Worker objeto manipula a exceção, o FirstChanceException evento é gerado somente no último domínio do aplicativo.When the last Worker object handles the exception, the FirstChanceException event is raised only in the last application domain. Os outros domínios de aplicativo nunca têm a chance de lidar com a exceção, portanto, o evento não é gerado.The other application domains never get a chance to handle the exception, so the event is not raised.

Quando o último Worker objeto não manipula a exceção, o FirstChanceException evento é gerado em cada domínio de aplicativo que tem um manipulador de eventos.When the last Worker object does not handle the exception, the FirstChanceException event is raised in each application domain that has an event handler. Após a conclusão de cada manipulador de eventos, a pilha continua desenrolando até que a exceção seja capturada pelo domínio de aplicativo padrão.After each event handler has finished, the stack continues to unwind until the exception is caught by the default application domain.

Observação

Para ver como a exibição da pilha aumenta à medida que o evento é aumentado de perto e mais próximo do domínio e.Exception.Message de e.Exception aplicativo padrão FirstChanceHandler , altere para nos manipuladores de eventos.To see how the stack display grows as the event is raised closer and closer to the default application domain, change e.Exception.Message to e.Exception in the FirstChanceHandler event handlers. Observe que quando TestException é chamado entre limites de domínio de aplicativo, ele aparece duas vezes: uma vez para o proxy e uma vez para o stub.Notice that when TestException is called across application domain boundaries, it appears twice: once for the proxy and once for the stub.

using System;
using System.Reflection;
using System.Runtime.ExceptionServices;

class Example
{
    static void Main()
    {
        AppDomain.CurrentDomain.FirstChanceException += FirstChanceHandler;

        // Create a set of application domains, with a Worker object in each one.
        // Each Worker object creates the next application domain.
        AppDomain ad = AppDomain.CreateDomain("AD0");
        Worker w = (Worker) ad.CreateInstanceAndUnwrap(
                                typeof(Worker).Assembly.FullName, "Worker");
        w.Initialize(0, 3);

        Console.WriteLine("\r\nThe last application domain throws an exception and catches it:");
        Console.WriteLine();
        w.TestException(true);

        try
        {
            Console.WriteLine(
                "\r\nThe last application domain throws an exception and does not catch it:");
            Console.WriteLine();
            w.TestException(false);
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine("ArgumentException caught in {0}: {1}", 
                AppDomain.CurrentDomain.FriendlyName, ex.Message);
        }
    }

    static void FirstChanceHandler(object source, FirstChanceExceptionEventArgs e)
    {
        Console.WriteLine("FirstChanceException event raised in {0}: {1}",
            AppDomain.CurrentDomain.FriendlyName, e.Exception.Message);
    }
}

public class Worker : MarshalByRefObject
{
    private AppDomain ad = null;
    private Worker w = null;

    public void Initialize(int count, int max)
    {
        // Handle the FirstChanceException event in all application domains except
        // AD1.
        if (count != 1)
        {
            AppDomain.CurrentDomain.FirstChanceException += FirstChanceHandler;
        }

        // Create another application domain, until the maximum is reached.
        // Field w remains null in the last application domain, as a signal
        // to TestException(). 
        if (count < max)
        {
            int next = count + 1;
            ad = AppDomain.CreateDomain("AD" + next);
            w = (Worker) ad.CreateInstanceAndUnwrap(
                             typeof(Worker).Assembly.FullName, "Worker");
            w.Initialize(next, max);
        }
    }

    public void TestException(bool handled)
    {
        // As long as there is another application domain, call TestException() on
        // its Worker object. When the last application domain is reached, throw a
        // handled or unhandled exception.
        if (w != null)
        {
            w.TestException(handled);
        }
        else if (handled)
        {
            try
            {
                throw new ArgumentException("Thrown in " + AppDomain.CurrentDomain.FriendlyName);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("ArgumentException caught in {0}: {1}", 
                    AppDomain.CurrentDomain.FriendlyName, ex.Message);
            }
        }
        else
        {
            throw new ArgumentException("Thrown in " + AppDomain.CurrentDomain.FriendlyName);
        }
    }

    static void FirstChanceHandler(object source, FirstChanceExceptionEventArgs e)
    {
        Console.WriteLine("FirstChanceException event raised in {0}: {1}",
            AppDomain.CurrentDomain.FriendlyName, e.Exception.Message);
    }
}

/* This example produces output similar to the following:

The last application domain throws an exception and catches it:

FirstChanceException event raised in AD3: Thrown in AD3
ArgumentException caught in AD3: Thrown in AD3

The last application domain throws an exception and does not catch it:

FirstChanceException event raised in AD3: Thrown in AD3
FirstChanceException event raised in AD2: Thrown in AD3
FirstChanceException event raised in AD0: Thrown in AD3
FirstChanceException event raised in Example.exe: Thrown in AD3
ArgumentException caught in Example.exe: Thrown in AD3
 */
Imports System.Reflection
Imports System.Runtime.ExceptionServices

Class Example

    Shared Sub Main()
    
        AddHandler AppDomain.CurrentDomain.FirstChanceException, AddressOf FirstChanceHandler

        ' Create a set of application domains, with a Worker object in each one.
        ' Each Worker object creates the next application domain.
        Dim ad As AppDomain = AppDomain.CreateDomain("AD0")
        Dim w As Worker = CType(ad.CreateInstanceAndUnwrap(
                                GetType(Worker).Assembly.FullName, "Worker"),
                                Worker)
        w.Initialize(0, 3)

        Console.WriteLine(vbCrLf & "The last application domain throws an exception and catches it:")
        Console.WriteLine()
        w.TestException(true)

        Try
            Console.WriteLine(vbCrLf & 
                "The last application domain throws an exception and does not catch it:")
            Console.WriteLine()
            w.TestException(false) 

        Catch ex As ArgumentException
        
            Console.WriteLine("ArgumentException caught in {0}: {1}", 
                AppDomain.CurrentDomain.FriendlyName, ex.Message)
        End Try
    End Sub

    Shared Sub FirstChanceHandler(ByVal source As Object, 
                                  ByVal e As FirstChanceExceptionEventArgs)
    
        Console.WriteLine("FirstChanceException event raised in {0}: {1}",
            AppDomain.CurrentDomain.FriendlyName, e.Exception.Message)
    End Sub
End Class

Public Class Worker
    Inherits MarshalByRefObject

    Private ad As AppDomain = Nothing
    Private w As Worker = Nothing

    Public Sub Initialize(ByVal count As Integer, ByVal max As Integer)
    
        ' Handle the FirstChanceException event in all application domains except
        ' AD1.
        If count <> 1
        
            AddHandler AppDomain.CurrentDomain.FirstChanceException, AddressOf FirstChanceHandler

        End If

        ' Create another application domain, until the maximum is reached.
        ' Field w remains Nothing in the last application domain, as a signal 
        ' to TestException(). 
        If count < max
            Dim nextAD As Integer = count + 1
            ad = AppDomain.CreateDomain("AD" & nextAD)
            w = CType(ad.CreateInstanceAndUnwrap(
                      GetType(Worker).Assembly.FullName, "Worker"),
                      Worker)
            w.Initialize(nextAD, max)
        End If
    End Sub

    Public Sub TestException(ByVal handled As Boolean)
    
        ' As long as there is another application domain, call TestException() on
        ' its Worker object. When the last application domain is reached, throw a
        ' handled or unhandled exception.
        If w IsNot Nothing
        
            w.TestException(handled)

        Else If handled
        
            Try
                Throw New ArgumentException("Thrown in " & AppDomain.CurrentDomain.FriendlyName)

            Catch ex As ArgumentException
            
                Console.WriteLine("ArgumentException caught in {0}: {1}", 
                    AppDomain.CurrentDomain.FriendlyName, ex.Message)
            End Try
        Else
        
            Throw New ArgumentException("Thrown in " & AppDomain.CurrentDomain.FriendlyName)
        End If
    End Sub

    Shared Sub FirstChanceHandler(ByVal source As Object, 
                                  ByVal e As FirstChanceExceptionEventArgs)
    
        Console.WriteLine("FirstChanceException event raised in {0}: {1}",
            AppDomain.CurrentDomain.FriendlyName, e.Exception.Message)
    End Sub
End Class

' This example produces output similar to the following:
'
'The last application domain throws an exception and catches it:
'
'FirstChanceException event raised in AD3: Thrown in AD3
'ArgumentException caught in AD3: Thrown in AD3
'
'The last application domain throws an exception and does not catch it:
'
'FirstChanceException event raised in AD3: Thrown in AD3
'FirstChanceException event raised in AD2: Thrown in AD3
'FirstChanceException event raised in AD0: Thrown in AD3
'FirstChanceException event raised in Example.exe: Thrown in AD3
'ArgumentException caught in Example.exe: Thrown in AD3

Comentários

Esse evento é apenas uma notificação.This event is only a notification. A manipulação desse evento não trata a exceção nem afeta a manipulação de exceção subsequente de forma alguma.Handling this event does not handle the exception or affect subsequent exception handling in any way. Depois que o evento tiver sido acionado e os manipuladores de eventos forem invocados, o Common Language Runtime (CLR) começará a procurar um manipulador para a exceção.After the event has been raised and event handlers have been invoked, the common language runtime (CLR) begins to search for a handler for the exception. FirstChanceExceptionfornece ao domínio do aplicativo uma primeira chance de examinar qualquer exceção gerenciada.FirstChanceException provides the application domain with a first chance to examine any managed exception.

O evento pode ser tratado por domínio de aplicativo.The event can be handled per application domain. Se um thread passar por vários domínios de aplicativo durante a execução de uma chamada, o evento será gerado em cada domínio de aplicativo que registrou um manipulador de eventos, antes que o CLR comece a procurar um manipulador de exceção correspondente no domínio do aplicativo.If a thread passes through multiple application domains while executing a call, the event is raised in each application domain that has registered an event handler, before the CLR begins searching for a matching exception handler in that application domain. Depois que o evento é tratado, uma pesquisa é feita para um manipulador de exceção correspondente no domínio do aplicativo.After the event has been handled, a search is made for a matching exception handler in that application domain. Se nenhum for encontrado, o evento será gerado no próximo domínio do aplicativo.If none is found, the event is raised in the next application domain.

Você deve lidar com todas as exceções que ocorrem no manipulador de eventos FirstChanceException para o evento.You must handle all exceptions that occur in the event handler for the FirstChanceException event. Caso contrário FirstChanceException , será gerado recursivamente.Otherwise, FirstChanceException is raised recursively. Isso pode resultar em um estouro de pilha e rescisão do aplicativo.This could result in a stack overflow and termination of the application. Recomendamos que você implemente manipuladores de eventos para esse evento como CERs (regiões de execução restrita), para manter exceções relacionadas à infraestrutura, como memória insuficiente ou estouro de pilha, de afetar a máquina virtual enquanto a notificação de exceção é sendo processado.We recommend that you implement event handlers for this event as constrained execution regions (CERs), to keep infrastructure-related exceptions such as out-of-memory or stack overflow from affecting the virtual machine while the exception notification is being processed.

Esse evento não é gerado para exceções que indicam a corrupção do estado do processo, como violações de acesso, a menos que o manipulador de eventos seja de HandleProcessCorruptedStateExceptionsAttribute segurança crítica e tenha o atributo.This event is not raised for exceptions that indicate corruption of process state, such as access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.

O Common Language Runtime suspende as anulações de thread enquanto esse evento de notificação está sendo tratado.The common language runtime suspends thread aborts while this notification event is being handled.

Segurança

SecurityCriticalAttribute
Requer confiança total para o chamador imediato.Requires full trust for the immediate caller. Este membro não pode ser usado pelo código transparente ou parcialmente confiável.This member cannot be used by partially trusted or transparent code.

Aplica-se a

Veja também