Classe StackTrace (System.Diagnostics)

Cambia visualizzazione:
ScriptFree
Riferimento a .NET Framework
Classe StackTrace
Il presente articolo è stato tradotto manualmente. Per visualizzare questa pagina e contemporaneamente visualizzarne il contenuto in lingua inglese, passare alla visualizzazione semplificata.

Rappresenta una traccia dello stack, vale a dire un insieme ordinato di uno o più stack frame.

Gerarchia di ereditarietà

System.Object
  System.Diagnostics.StackTrace

Spazio dei nomi:  System.Diagnostics
Assembly:  mscorlib (in mscorlib.dll)
Sintassi

Visual Basic
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
<SecurityPermissionAttribute(SecurityAction.InheritanceDemand, UnmanagedCode := True)> _
Public Class StackTrace
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
public class StackTrace
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
[SecurityPermissionAttribute(SecurityAction::InheritanceDemand, UnmanagedCode = true)]
public ref class StackTrace
F#
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
[<SecurityPermissionAttribute(SecurityAction.InheritanceDemand, UnmanagedCode = true)>]
type StackTrace =  class end

Il tipo StackTrace espone i seguenti membri.

Costruttori

  Nome Descrizione
Metodo pubblico StackTrace() Inizializza una nuova istanza della classe StackTrace dal frame del chiamante.
Metodo pubblico StackTrace(Boolean) Inizializza una nuova istanza della classe StackTrace dal frame del chiamante, acquisendo facoltativamente informazioni sull'origine.
Metodo pubblico StackTrace(Exception) Inizializza una nuova istanza della classe StackTrace utilizzando l'oggetto eccezione fornito.
Metodo pubblico StackTrace(Int32) Inizializza una nuova istanza della classe StackTrace dal frame del chiamante, ignorando il numero di frame specificato.
Metodo pubblico StackTrace(StackFrame) Consente di inizializzare una nuova istanza della classe StackTrace che contiene un solo frame.
Metodo pubblico StackTrace(Exception, Boolean) Inizializza una nuova istanza della classe StackTrace, utilizzando l'oggetto eccezione fornito e facoltativamente acquisendo informazioni sull'origine.
Metodo pubblico StackTrace(Exception, Int32) Inizializza una nuova istanza della classe StackTrace utilizzando l'oggetto eccezione fornito e ignorando il numero di frame specificato.
Metodo pubblico StackTrace(Int32, Boolean) Inizializza una nuova istanza della classe StackTrace dal frame del chiamante, ignorando il numero di frame specificato ed eventualmente acquisendo le informazioni sull'origine.
Metodo pubblico StackTrace(Thread, Boolean) Inizializza una nuova istanza della classe StackTrace per un thread specifico, acquisendo facoltativamente informazioni sull'origine.
Metodo pubblico StackTrace(Exception, Int32, Boolean) Inizializza una nuova istanza della classe StackTrace utilizzando l'oggetto eccezione fornito, ignorando il numero di frame specificato ed eventualmente acquisendo le informazioni sull'origine.
In alto
Proprietà

  Nome Descrizione
Proprietà pubblica FrameCount Ottiene il numero di frame nella traccia dello stack.
In alto
Metodi

  Nome Descrizione
Metodo pubblico Equals(Object) Determina se l'oggetto Object specificato è uguale all'oggetto Object corrente. (Ereditato da Object)
Metodo protetto Finalize Consente a un oggetto di provare a liberare risorse ed eseguire altre operazioni di pulitura prima che l'oggetto stesso venga recuperato dalla procedura di Garbage Collection. (Ereditato da Object)
Metodo pubblico GetFrame Ottiene lo stack frame specificato.
Metodo pubblico GetFrames Restituisce una copia di tutti gli stack frame nella traccia dello stack corrente.
Metodo pubblico GetHashCode Funge da funzione hash per un determinato tipo. (Ereditato da Object)
Metodo pubblico GetType Ottiene l'oggetto Type dell'istanza corrente. (Ereditato da Object)
Metodo protetto MemberwiseClone Consente di creare una copia dei riferimenti dell'oggetto Object corrente. (Ereditato da Object)
Metodo pubblico ToString Compila una rappresentazione leggibile della traccia dello stack. (Esegue l'override di Object.ToString()).
In alto
Campi

  Nome Descrizione
Campo pubblico Membro statico METHODS_TO_SKIP Definisce l'impostazione predefinita per il numero di metodi da omettere dalla traccia dello stack. Questo campo è costante.
In alto
Note

Le informazioni di StackTrace sono maggiori con le configurazioni di debug. Per impostazione predefinita, a differenza delle build di rilascio, le build di debug comprendono simboli di debug. Questi simboli contengono la maggior parte delle informazioni sul file, il nome del metodo, il numero di riga e la colonna utilizzate per la costruzione di oggetti StackFrame e StackTrace.

A causa di trasformazioni di codice eseguite durante l'ottimizzazione, è possibile che StackTrace non riporti il numero di chiamate al metodo previsto.

Esempi

Nell'applicazione console riportata di seguito viene illustrato come creare un oggetto StackTrace semplice e scorrerne i frame per ottenere informazioni diagnostiche e di debug.

Visual Basic

Imports System
Imports System.Diagnostics

Class StackTraceSample

    <STAThread()>  _
    Public Shared Sub Main()

        Dim sample As New StackTraceSample()
        Try

            sample.MyPublicMethod()
        Catch
            ' Create a StackTrace that captures
            ' filename, line number, and column
            ' information for the current thread.
            Dim st As New StackTrace(True)
            Dim i As Integer

            For i = 0 To st.FrameCount - 1

                ' Note that high up the call stack, there is only
                ' one stack frame.
                Dim sf As StackFrame = st.GetFrame(i)
                Console.WriteLine()
                Console.WriteLine("High up the call stack, Method: {0}", _
                    sf.GetMethod())

                Console.WriteLine("High up the call stack, Line Number: {0}", _
                    sf.GetFileLineNumber())
            Next i
        End Try
    End Sub

   Public Sub MyPublicMethod()
      MyProtectedMethod()
   End Sub

   Protected Sub MyProtectedMethod()
      Dim mic As New MyInternalClass()
      mic.ThrowsException()
   End Sub


   Class MyInternalClass

      Public Sub ThrowsException()
         Try
            Throw New Exception("A problem was encountered.")
         Catch e As Exception

            ' Create a StackTrace that captures filename,
            ' line number and column information.
            Dim st As New StackTrace(True)

            Dim stackIndent As String = ""
            Dim i As Integer
            For i = 0 To st.FrameCount - 1
               ' Note that at this level, there are four
               ' stack frames, one for each method invocation.
               Dim sf As StackFrame = st.GetFrame(i)
               Console.WriteLine()
               Console.WriteLine(stackIndent + " Method: {0}", _
                   sf.GetMethod())
               Console.WriteLine(stackIndent + " File: {0}", _
                   sf.GetFileName())
               Console.WriteLine(stackIndent + " Line Number: {0}", _
                   sf.GetFileLineNumber())
               stackIndent += "  "
            Next i
            Throw e
         End Try
      End Sub
   End Class
End Class


' This console application produces the following output when
' compiled with the Debug configuration.
'   
'    Method: Void ThrowsException()
'    File: c:\pp\samples\stacktraceframe\myclass.vb
'    Line Number: 55
' 
'      Method: Void MyProtectedMethod()
'      File: c:\pp\samples\stacktraceframe\myclass.vb
'      Line Number: 42
' 
'        Method: Void MyPublicMethod()
'        File: c:\pp\samples\stacktraceframe\myclass.vb
'        Line Number: 37
' 
'          Method: Void Main(System.String[])
'          File: c:\pp\samples\stacktraceframe\myclass.vb
'          Line Number: 13
' 
'   High up the call stack, Method: Void Main(System.String[])
'   High up the call stack, Line Number: 18
' 
' 
' This console application produces the following output when
' compiled with the Release configuration.
' 
'    Method: Void ThrowsException()
'    File:
'    Line Number: 0
' 
'      Method: Void Main(System.String[])
'      File:
'      Line Number: 0
' 
'   High up the call stack, Method: Void Main()
'   High up the call stack, Line Number: 0
'


C#

using System;
using System.Diagnostics;

class StackTraceSample
{
    [STAThread]
    static void Main(string[] args)
    {
        StackTraceSample sample = new StackTraceSample();
        try
        {
            sample.MyPublicMethod();
        }
        catch (Exception)
        {
            // Create a StackTrace that captures
            // filename, line number, and column
            // information for the current thread.
            StackTrace st = new StackTrace(true);
            for(int i =0; i< st.FrameCount; i++ )
            {
                // Note that high up the call stack, there is only
                // one stack frame.
                StackFrame sf = st.GetFrame(i);
                Console.WriteLine();
                Console.WriteLine("High up the call stack, Method: {0}",
                    sf.GetMethod());

                Console.WriteLine("High up the call stack, Line Number: {0}",
                    sf.GetFileLineNumber());
            }
        }
    }

    public void MyPublicMethod () 
    { 
        MyProtectedMethod(); 
    }

    protected void MyProtectedMethod ()
    {
        MyInternalClass mic = new MyInternalClass();
        mic.ThrowsException();
    }

    class MyInternalClass
    {
        public void ThrowsException()
        {
            try
            {
                throw new Exception("A problem was encountered.");
            }
            catch (Exception e)
            {
                // Create a StackTrace that captures filename,
                // line number and column information.
                StackTrace st = new StackTrace(true);
                string stackIndent = "";
                for(int i =0; i< st.FrameCount; i++ )
                {
                    // Note that at this level, there are four
                    // stack frames, one for each method invocation.
                    StackFrame sf = st.GetFrame(i);
                    Console.WriteLine();
                    Console.WriteLine(stackIndent + " Method: {0}",
                        sf.GetMethod() );
                    Console.WriteLine(  stackIndent + " File: {0}", 
                        sf.GetFileName());
                    Console.WriteLine(  stackIndent + " Line Number: {0}",
                        sf.GetFileLineNumber());
                    stackIndent += "  ";
                }
                throw e;
            }
        }
    }
}

/*
This console application produces the following output when
compiled with the Debug configuration.

   Method: Void ThrowsException()
   File: c:\samples\stacktraceframe\myclass.cs
   Line Number: 59

     Method: Void MyProtectedMethod()
     File: c:\samples\stacktraceframe\myclass.cs
     Line Number: 45

       Method: Void MyPublicMethod()
       File: c:\samples\stacktraceframe\myclass.cs
       Line Number: 39

         Method: Void Main(System.String[])
         File: c:\samples\stacktraceframe\myclass.cs
         Line Number: 13

  High up the call stack, Method: Void Main(System.String[])
  High up the call stack, Line Number: 20


This console application produces the following output when
compiled with the Release configuration.

   Method: Void ThrowsException()
   File:
   Line Number: 0

     Method: Void Main(System.String[])
     File:
     Line Number: 0

  High up the call stack, Method: Void Main(System.String[])
  High up the call stack, Line Number: 0

*/


Visual C++

#using <System.dll>

using namespace System;
using namespace System::Diagnostics;
ref class StackTraceSample
{
private:
   ref class MyInternalClass
   {
   public:
      void ThrowsException()
      {
         try
         {
            throw gcnew Exception( "A problem was encountered." );
         }
         catch ( Exception^ e ) 
         {

            // Create a StackTrace that captures
            // filename, line number, and column
            // information for the current thread.
            StackTrace^ st = gcnew StackTrace( true );
            String^ stackIndent = "";
            for ( int i = 0; i < st->FrameCount; i++ )
            {

               // Note that at this level, there are five
               // stack frames, one for each method invocation.
               StackFrame^ sf = st->GetFrame( i );
               Console::WriteLine();
               Console::WriteLine( "{0}Method: {1}", stackIndent, sf->GetMethod() );
               Console::WriteLine( "{0}File: {1}", stackIndent, sf->GetFileName() );
               Console::WriteLine( "{0}Line Number: {1}", stackIndent, sf->GetFileLineNumber().ToString() );
               stackIndent = String::Concat( stackIndent, "  " );

            }
            throw e;
         }

      }

   };


protected:
   void MyProtectedMethod()
   {
      MyInternalClass^ mic = gcnew MyInternalClass;
      mic->ThrowsException();
   }


public:
   void MyPublicMethod()
   {
      MyProtectedMethod();
   }

};

int main()
{
   StackTraceSample^ sample = gcnew StackTraceSample;
   try
   {
      sample->MyPublicMethod();
   }
   catch ( Exception^ ) 
   {

      // Create a StackTrace that captures
      // filename, line number, and column
      // information for the current thread.
      StackTrace^ st = gcnew StackTrace( true );
      for ( int i = 0; i < st->FrameCount; i++ )
      {

         // For an executable built from C++, there
         // are two stack frames here: one for main,
         // and one for the _mainCRTStartup stub. 
         StackFrame^ sf = st->GetFrame( i );
         Console::WriteLine();
         Console::WriteLine( "High up the call stack, Method: {0}", sf->GetMethod()->ToString() );
         Console::WriteLine( "High up the call stack, Line Number: {0}", sf->GetFileLineNumber().ToString() );

      }
   }

}

/*
This console application produces the following output when
compiled with the Debug configuration.

  Method: Void ThrowsException()
  File: c:\samples\stacktraceframe\myclass.cpp
  Line Number: 20

    Method: Void MyProtectedMethod()
    File: c:\samples\stacktraceframe\myclass.cpp
    Line Number: 45

      Method: Void MyPublicMethod()
      File: c:\samples\stacktraceframe\myclass.cpp
      Line Number: 50

        Method: Int32 main()
        File: c:\samples\stacktraceframe\myclass.cpp
        Line Number: 56

          Method: UInt32 _mainCRTStartup()
          File:
          Line Number: 0

  High up the call stack, Method: Int32 main()
  High up the call stack, Line Number: 62

  High up the call stack, Method: UInt32 _mainCRTStartup()
  High up the call stack, Line Number: 0

This console application produces the following output when
compiled with the Release configuration.

  Method: Void ThrowsException()
  File:
  Line Number: 0

    Method: Int32 main()
    File:
    Line Number: 0

      Method: UInt32 _mainCRTStartup()
      File:
      Line Number: 0

  High up the call stack, Method: Int32 main()
  High up the call stack, Line Number: 0

  High up the call stack, Method: UInt32 _mainCRTStartup()
  High up the call stack, Line Number: 0

*/


Informazioni sulla versione

.NET Framework

Supportato in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supportato in: 4, 3.5 SP1
Sicurezza di .NET Framework

Piattaforme

Windows 7, Windows Vista SP1 o versione successiva, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (componenti di base del server non supportati), Windows Server 2008 R2 (componenti di base del server supportati con SP1 o versione successiva), Windows Server 2003 SP2

.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema di .NET Framework.
Codice thread safe

Qualsiasi membro static (Shared in Visual Basic) pubblico di questo tipo è thread-safe. I membri di istanza non sono garantiti come thread-safe.
Vedere anche

Riferimenti