AppDomain.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.

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) 
属性

示例

下面的示例通过 AD3创建一系列名为 AD0 的应用程序域,并在每个应用程序域中创建一个 Worker 对象。The following example creates a series of application domains named AD0 through AD3, with a Worker object in each application domain. 每个 Worker 对象都有一个对下一个应用程序域中 Worker 对象的引用,但最后一个应用程序域中的 Worker 除外。Each Worker object has a reference to the Worker object in the next application domain, except for the Worker in the last application domain. FirstChanceException 事件在除 AD1之外的所有应用程序域中进行处理。The FirstChanceException event is handled in all application domains except AD1.

备注

除了在多个应用程序域中演示第一次异常通知的示例外,你可以在如何:接收首次异常通知中找到简单的用例。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.

创建应用程序域后,默认应用程序域将为第一个应用程序域调用 TestException 方法。When the application domains have been created, the default application domain calls the TestException method for the first application domain. 每个 Worker 对象将调用下一个应用程序域的 TestException 方法,直到最后一个 Worker 引发处理或未处理的异常。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. 因此,当前线程通过所有应用程序域,并将 TestException 添加到每个应用程序域中的堆栈中。Thus, the current thread passes through all the application domains, and TestException is added to the stack in each application domain.

当最后一个 Worker 对象处理异常时,只会在最后一个应用程序域中引发 FirstChanceException 事件。When the last Worker object handles the exception, the FirstChanceException event is raised only in the last application domain. 其他应用程序域绝不会有机会处理异常,因此不会引发事件。The other application domains never get a chance to handle the exception, so the event is not raised.

当最后一个 Worker 对象未处理异常时,将在具有事件处理程序的每个应用程序域中引发 FirstChanceException 事件。When the last Worker object does not handle the exception, the FirstChanceException event is raised in each application domain that has an event handler. 每个事件处理程序完成后,堆栈将继续展开,直到默认应用程序域捕获到该异常。After each event handler has finished, the stack continues to unwind until the exception is caught by the default application domain.

备注

若要查看随着事件更近且更接近默认应用程序域,堆栈显示的增长方式,请将 e.Exception.Message 更改为 FirstChanceHandler 事件处理程序中的 e.ExceptionTo 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. 请注意,当跨应用程序域边界调用 TestException 时,它会出现两次:一次用于代理,一次用于存根。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

注解

此事件只是一个通知。This event is only a notification. 处理此事件不会处理异常,也不会影响后续的异常处理。Handling this event does not handle the exception or affect subsequent exception handling in any way. 引发事件并调用事件处理程序后,公共语言运行时(CLR)开始搜索异常的处理程序。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. FirstChanceException 提供了应用程序域,并具有检查任何托管异常的第一次机会。FirstChanceException provides the application domain with a first chance to examine any managed exception.

可以按应用程序域处理事件。The event can be handled per application domain. 如果线程在执行调用时传递到多个应用程序域,则会在已注册事件处理程序的每个应用程序域中引发事件,然后 CLR 开始在该应用程序域中搜索匹配的异常处理程序。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. 处理事件后,会在该应用程序域中搜索匹配的异常处理程序。After the event has been handled, a search is made for a matching exception handler in that application domain. 如果未找到任何内容,则会在下一个应用程序域中引发事件。If none is found, the event is raised in the next application domain.

您必须处理 FirstChanceException 事件的事件处理程序中发生的所有异常。You must handle all exceptions that occur in the event handler for the FirstChanceException event. 否则,将以递归方式引发 FirstChanceExceptionOtherwise, FirstChanceException is raised recursively. 这可能导致堆栈溢出和终止应用程序。This could result in a stack overflow and termination of the application. 我们建议你将此事件的事件处理程序实现为受约束的执行区域(Cer),以将与基础结构相关的异常(如内存不足或堆栈溢出)与影响虚拟机有关,同时引发异常通知正在处理。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.

对于指示进程状态损坏(如访问冲突)的异常,不会引发此事件,除非事件处理程序是安全关键的并且具有 HandleProcessCorruptedStateExceptionsAttribute 特性。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.

当处理此通知事件时,公共语言运行时挂起线程中止。The common language runtime suspends thread aborts while this notification event is being handled.

安全性

SecurityCriticalAttribute
需要对直接调用方的完全信任。Requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

适用于

另请参阅