AppDomain.FirstChanceException Olay

Tanım

Yönetilen kodda bir özel durum oluşturulduğunda, çalışma zamanı, uygulama etki alanındaki bir özel durum işleyicisi için çağrı yığınını aramadan önce gerçekleşir.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;
public event EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs>? FirstChanceException;
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> 
[<add: System.Security.SecurityCritical>]
[<remove: System.Security.SecurityCritical>]
member this.FirstChanceException : EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> 
Public Custom Event FirstChanceException As EventHandler(Of FirstChanceExceptionEventArgs) 

Olay Türü

EventHandler<FirstChanceExceptionEventArgs>
Öznitelikler

Örnekler

Aşağıdaki örnek AD0 AD3 , Worker her uygulama etki alanında bir nesnesi ile ile adlı bir dizi uygulama etki alanı oluşturur.The following example creates a series of application domains named AD0 through AD3, with a Worker object in each application domain. Her bir Worker nesne, Worker Worker son uygulama etki alanında hariç olmak üzere bir sonraki uygulama etki alanındaki nesnesine bir başvuru içerir.Each Worker object has a reference to the Worker object in the next application domain, except for the Worker in the last application domain. FirstChanceExceptionOlay, hariç tüm uygulama etki alanlarında işlenir AD1 .The FirstChanceException event is handled in all application domains except AD1.

Not

Birden çok uygulama etki alanında birinci şans özel durum bildirimlerini gösteren bu örneğe ek olarak, nasıl yapılır: First-Chance özel durum bildirimleri alma' da basit kullanım örnekleri bulabilirsiniz.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.

Uygulama etki alanları oluşturulduğunda, varsayılan uygulama etki alanı TestException ilk uygulama etki alanı için yöntemini çağırır.When the application domains have been created, the default application domain calls the TestException method for the first application domain. Her Worker nesne, TestException son olarak Worker işlenen veya işlenmemiş bir özel durum oluşturursa, sonraki uygulama etki alanı için yöntemini çağırır.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. Bu nedenle, geçerli iş parçacığı tüm uygulama etki alanlarından geçer ve TestException her uygulama etki alanındaki yığına eklenir.Thus, the current thread passes through all the application domains, and TestException is added to the stack in each application domain.

Son Worker nesne özel durumu işlediğinde, FirstChanceException olay yalnızca son uygulama etki alanında tetiklenir.When the last Worker object handles the exception, the FirstChanceException event is raised only in the last application domain. Diğer uygulama etki alanları hiçbir şekilde özel durum işleme şansı almaz, bu nedenle olay oluşturulmaz.The other application domains never get a chance to handle the exception, so the event is not raised.

Son Worker nesne özel durumu işlemezse olay FirstChanceException işleyicisi olan her uygulama etki alanında olay tetiklenir.When the last Worker object does not handle the exception, the FirstChanceException event is raised in each application domain that has an event handler. Her olay işleyicisi tamamlandıktan sonra, özel durum varsayılan uygulama etki alanı tarafından yakalanana kadar yığın geriye devam eder.After each event handler has finished, the stack continues to unwind until the exception is caught by the default application domain.

Not

Olay, varsayılan uygulama etki alanına daha yakın ve daha yakın bir şekilde harekete geçirilir ve olay e.Exception.Message işleyicilerinde ' e geçin e.Exception FirstChanceHandler .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. TestExceptionUygulama etki alanı sınırları arasında çağrıldığında, iki kez göründüğünü unutmayın: proxy için bir kez ve saplama için bir kez.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

Açıklamalar

Bu olay yalnızca bir bildirimdir.This event is only a notification. Bu olayı işlemek özel durumu işlemez veya sonraki özel durum işlemesini herhangi bir şekilde etkilemez.Handling this event does not handle the exception or affect subsequent exception handling in any way. Olay tetiklenir ve olay işleyicileri çağrıldıktan sonra, ortak dil çalışma zamanı (CLR) özel durum için bir işleyici aramaya başlar.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 yönetilen herhangi bir özel durumu incelemek için uygulama etki alanına bir ilk şans sağlar.FirstChanceException provides the application domain with a first chance to examine any managed exception.

Olay, uygulama etki alanı başına işlenebilir.The event can be handled per application domain. Bir iş parçacığı, bir çağrıyı yürütürken birden çok uygulama etki alanından geçerse, CLR bu uygulama etki alanında eşleşen bir özel durum işleyicisini aramaya başlamadan önce olay işleyicisi olan her bir uygulama etki alanında tetiklenir.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. Olay işlendikten sonra, bu uygulama etki alanında eşleşen özel durum işleyicisi için bir arama yapılır.After the event has been handled, a search is made for a matching exception handler in that application domain. Hiçbiri bulunmazsa, olay sonraki uygulama etki alanında oluşturulur.If none is found, the event is raised in the next application domain.

Olay işleyicisinde oluşan tüm özel durumları işlemeniz gerekir FirstChanceException .You must handle all exceptions that occur in the event handler for the FirstChanceException event. Aksi takdirde, FirstChanceException yinelemeli olarak oluşturulur.Otherwise, FirstChanceException is raised recursively. Bu, uygulamanın yığın taşmasına ve sonlandırmasına yol açabilir.This could result in a stack overflow and termination of the application. Bu olay için olay işleyicilerini kısıtlı yürütme bölgeleri (CERs) olarak uygulamanızı öneririz. Bu, özel durum bildirimi işlenirken, sanal makineyi etkilemeden bellek dışı veya yığın taşması gibi altyapı ile ilgili özel durumların tutulmasını sağlar.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.

Bu olay, olay işleyicisi güvenlik açısından kritik olmadığı ve özniteliğine sahip olmadığı sürece, erişim ihlalleri gibi işlem durumunun bozulmasını belirten özel durumlar için oluşmaz 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.

Ortak dil çalışma zamanı, bu bildirim olayı işlendiği sırada iş parçacığını askıya alır.The common language runtime suspends thread aborts while this notification event is being handled.

Şunlara uygulanır

Ayrıca bkz.