StackTrace Construtores

Definição

Inicializa uma nova instância da StackTrace classe.

Sobrecargas

Name Description
StackTrace()

Inicializa uma nova instância da StackTrace classe a partir do quadro do chamador.

StackTrace(Boolean)

Inicializa uma nova instância da StackTrace classe a partir do frame do chamador, capturando opcionalmente a informação de origem.

StackTrace(StackFrame)

Inicializa uma nova instância da StackTrace classe que contém um único frame.

StackTrace(Exception)

Inicializa uma nova instância da StackTrace classe usando o objeto de exceção fornecido.

StackTrace(Int32)

Inicializa uma nova instância da StackTrace classe a partir do frame do chamador, saltando o número especificado de frames.

StackTrace(Exception, Int32)

Inicializa uma nova instância da StackTrace classe usando o objeto exceção fornecido e saltando o número especificado de frames.

StackTrace(Int32, Boolean)

Inicializa uma nova instância da StackTrace classe a partir do frame do chamador, saltando o número especificado de frames e capturando opcionalmente informação de origem.

StackTrace(Thread, Boolean)
Obsoleto.

Inicializa uma nova instância da StackTrace classe para um thread específico, capturando opcionalmente a informação da fonte.

Não use esta sobrecarga de construtores.

StackTrace(Exception, Int32, Boolean)

Inicializa uma nova instância da StackTrace classe usando o objeto exceção fornecido, saltando o número especificado de frames e capturando opcionalmente a informação da fonte.

StackTrace(Exception, Boolean)

Inicializa uma nova instância da StackTrace classe, usando o objeto de exceção fornecido e opcionalmente capturando a informação da fonte.

StackTrace()

Inicializa uma nova instância da StackTrace classe a partir do quadro do chamador.

public:
 StackTrace();
public StackTrace();
Public Sub New ()

Exemplos

O exemplo de código seguinte mostra as primeiras e últimas chamadas de função numa linha de pilha.

public void Level5Method()
{
   try
   {
      ClassLevel6 nestedClass = new ClassLevel6();
      nestedClass.Level6Method();
   }
   catch (Exception e)
   {
      Console.WriteLine(" Level5Method exception handler");

      StackTrace st = new StackTrace();

      // Display the most recent function call.
      StackFrame sf = st.GetFrame(0);
      Console.WriteLine();
      Console.WriteLine("  Exception in method: ");
      Console.WriteLine("      {0}", sf.GetMethod());

      if (st.FrameCount >1)
      {
         // Display the highest-level function call
         // in the trace.
         sf = st.GetFrame(st.FrameCount-1);
         Console.WriteLine("  Original function call at top of call stack):");
         Console.WriteLine("      {0}", sf.GetMethod());
      }

      Console.WriteLine();
      Console.WriteLine("   ... throwing exception to next level ...");
      Console.WriteLine("-------------------------------------------------\n");
      throw e;
   }
}
Public Sub Level5Method()
   Try
      Dim nestedClass As New ClassLevel6()
      nestedClass.Level6Method()
   Catch e As Exception
      Console.WriteLine(" Level5Method exception handler")
      
      Dim st As New StackTrace()
      
      ' Display the most recent function call.
      Dim sf As StackFrame = st.GetFrame(0)
      Console.WriteLine()
      Console.WriteLine("  Exception in method: ")
      Console.WriteLine("      {0}", sf.GetMethod())
      
      If st.FrameCount > 1 Then
         ' Display the highest-level function call in the trace.
         sf = st.GetFrame((st.FrameCount - 1))
         Console.WriteLine("  Original function call at top of call stack):")
         Console.WriteLine("      {0}", sf.GetMethod())
      End If
      
      Console.WriteLine()
      Console.WriteLine("   ... throwing exception to next level ...")
      Console.WriteLine("-------------------------------------------------")
      Console.WriteLine()
      Throw e
   End Try
End Sub

Observações

O StackTrace é criado com a thread atual do chamador e não contém nome de ficheiro, número de linha ou informação de coluna.

Use este construtor sem parâmetros quando quiser um traçado completo com apenas informação do método resumo sobre a pilha de chamadas.

Aplica-se a

StackTrace(Boolean)

Inicializa uma nova instância da StackTrace classe a partir do frame do chamador, capturando opcionalmente a informação de origem.

public:
 StackTrace(bool fNeedFileInfo);
public StackTrace(bool fNeedFileInfo);
new System.Diagnostics.StackTrace : bool -> System.Diagnostics.StackTrace
Public Sub New (fNeedFileInfo As Boolean)

Parâmetros

fNeedFileInfo
Boolean

true para capturar o nome do ficheiro, número da linha e número da coluna; caso contrário, false.

Exemplos

O exemplo de código seguinte demonstra vários StackTrace métodos de construtor.

public void Level2Method()
{
   try
   {
      ClassLevel3 nestedClass = new ClassLevel3();
      nestedClass.Level3Method();
   }
   catch (Exception e)
   {
      Console.WriteLine(" Level2Method exception handler");

      // Display the full call stack at this level.
      StackTrace st1 = new StackTrace(true);
      Console.WriteLine(" Stack trace for this level: {0}",
         st1.ToString());

      // Build a stack trace from one frame, skipping the current
      // frame and using the next frame.
      StackTrace st2 = new StackTrace(new StackFrame(1, true));
      Console.WriteLine(" Stack trace built with next level frame: {0}",
         st2.ToString());

      // Build a stack trace skipping the current frame, and
      // including all the other frames.
      StackTrace st3 = new StackTrace(1, true);
      Console.WriteLine(" Stack trace built from the next level up: {0}",
         st3.ToString());

      Console.WriteLine();
      Console.WriteLine("   ... throwing exception to next level ...");
      Console.WriteLine("-------------------------------------------------\n");
      throw e;
   }
}
Public Sub Level2Method()
   Try
      Dim nestedClass As New ClassLevel3
      nestedClass.Level3Method()
   
   Catch e As Exception
      Console.WriteLine(" Level2Method exception handler")
      
      ' Display the full call stack at this level.
      Dim st1 As New StackTrace(True)
      Console.WriteLine(" Stack trace for this level: {0}", _
         st1.ToString())
      
      ' Build a stack trace from one frame, skipping the current
      ' frame and using the next frame.
      Dim st2 As New StackTrace(New StackFrame(1, True))
      Console.WriteLine(" Stack trace built with next level frame: {0}", _
          st2.ToString())
      
      ' Build a stack trace skipping the current frame, and
      ' including all the other frames.
      Dim st3 As New StackTrace(1, True)
      Console.WriteLine(" Stack trace built from the next level up: {0}", _
          st3.ToString())
      
      Console.WriteLine()
      Console.WriteLine("   ... throwing exception to next level ...")
      Console.WriteLine("-------------------------------------------------")
      Console.WriteLine()
      Throw e
   End Try
End Sub

Observações

O StackTrace é criado com o tópico atual do chamador.

Aplica-se a

StackTrace(StackFrame)

Inicializa uma nova instância da StackTrace classe que contém um único frame.

public:
 StackTrace(System::Diagnostics::StackFrame ^ frame);
public StackTrace(System.Diagnostics.StackFrame frame);
new System.Diagnostics.StackTrace : System.Diagnostics.StackFrame -> System.Diagnostics.StackTrace
Public Sub New (frame As StackFrame)

Parâmetros

frame
StackFrame

A moldura que o StackTrace objeto deve conter.

Exemplos

O exemplo de código seguinte escreve informação de rastreio de pilha numa entrada de registo de eventos.

StackFrame fr = new StackFrame(1,true);
StackTrace st = new StackTrace(fr);
EventLog.WriteEntry(fr.GetMethod().Name,
                    st.ToString(),
                    EventLogEntryType.Warning);
Dim frame As New StackFrame(1, True)
Dim strace As New StackTrace(frame)            

EventLog.WriteEntry(frame.GetMethod().Name, _
                    strace.ToString(), _
                    EventLogEntryType.Warning)

Observações

Usa este construtor quando não quiseres o overhead de um traço de stack completo.

Ver também

Aplica-se a

StackTrace(Exception)

Inicializa uma nova instância da StackTrace classe usando o objeto de exceção fornecido.

public:
 StackTrace(Exception ^ e);
public StackTrace(Exception e);
new System.Diagnostics.StackTrace : Exception -> System.Diagnostics.StackTrace
Public Sub New (e As Exception)

Parâmetros

e
Exception

O objeto exceção a partir do qual construir o traço de pilha.

Exceções

O parâmetro e é null.

Observações

O StackTrace é criado com a thread atual do chamador e não contém nome de ficheiro, número de linha ou informação de coluna.

O traço de pilha resultante descreve a pilha no momento da exceção.

Ver também

Aplica-se a

StackTrace(Int32)

Inicializa uma nova instância da StackTrace classe a partir do frame do chamador, saltando o número especificado de frames.

public:
 StackTrace(int skipFrames);
public StackTrace(int skipFrames);
new System.Diagnostics.StackTrace : int -> System.Diagnostics.StackTrace
Public Sub New (skipFrames As Integer)

Parâmetros

skipFrames
Int32

O número de frames na pilha a partir do qual se deve iniciar o rastreio.

Exceções

O skipFrames parâmetro é negativo.

Observações

O StackTrace é criado com a thread atual do chamador e não contém nome de ficheiro, número de linha ou informação de coluna.

Se o número de frames a saltar for maior ou igual ao número total de frames na pilha de chamadas no momento em que a instância é criada, não StackTrace conterão frames.

Aplica-se a

StackTrace(Exception, Int32)

Inicializa uma nova instância da StackTrace classe usando o objeto exceção fornecido e saltando o número especificado de frames.

public:
 StackTrace(Exception ^ e, int skipFrames);
public StackTrace(Exception e, int skipFrames);
new System.Diagnostics.StackTrace : Exception * int -> System.Diagnostics.StackTrace
Public Sub New (e As Exception, skipFrames As Integer)

Parâmetros

e
Exception

O objeto exceção a partir do qual construir o traço de pilha.

skipFrames
Int32

O número de frames na pilha a partir do qual se deve iniciar o rastreio.

Exceções

O parâmetro e é null.

O skipFrames parâmetro é negativo.

Observações

Não StackTrace contém nome de ficheiro, número de linha ou informação de coluna.

O traço de pilha resultante descreve a pilha no momento da exceção.

Se o número de frames a saltar for maior ou igual ao número total de frames na pilha de chamadas no momento em que a instância é criada, não StackTrace conterão frames.

Ver também

Aplica-se a

StackTrace(Int32, Boolean)

Inicializa uma nova instância da StackTrace classe a partir do frame do chamador, saltando o número especificado de frames e capturando opcionalmente informação de origem.

public:
 StackTrace(int skipFrames, bool fNeedFileInfo);
public StackTrace(int skipFrames, bool fNeedFileInfo);
new System.Diagnostics.StackTrace : int * bool -> System.Diagnostics.StackTrace
Public Sub New (skipFrames As Integer, fNeedFileInfo As Boolean)

Parâmetros

skipFrames
Int32

O número de frames na pilha a partir do qual se deve iniciar o rastreio.

fNeedFileInfo
Boolean

true para capturar o nome do ficheiro, número da linha e número da coluna; caso contrário, false.

Exceções

O skipFrames parâmetro é negativo.

Exemplos

O exemplo de código seguinte demonstra vários StackTrace métodos de construtor.

public void Level2Method()
{
   try
   {
      ClassLevel3 nestedClass = new ClassLevel3();
      nestedClass.Level3Method();
   }
   catch (Exception e)
   {
      Console.WriteLine(" Level2Method exception handler");

      // Display the full call stack at this level.
      StackTrace st1 = new StackTrace(true);
      Console.WriteLine(" Stack trace for this level: {0}",
         st1.ToString());

      // Build a stack trace from one frame, skipping the current
      // frame and using the next frame.
      StackTrace st2 = new StackTrace(new StackFrame(1, true));
      Console.WriteLine(" Stack trace built with next level frame: {0}",
         st2.ToString());

      // Build a stack trace skipping the current frame, and
      // including all the other frames.
      StackTrace st3 = new StackTrace(1, true);
      Console.WriteLine(" Stack trace built from the next level up: {0}",
         st3.ToString());

      Console.WriteLine();
      Console.WriteLine("   ... throwing exception to next level ...");
      Console.WriteLine("-------------------------------------------------\n");
      throw e;
   }
}
Public Sub Level2Method()
   Try
      Dim nestedClass As New ClassLevel3
      nestedClass.Level3Method()
   
   Catch e As Exception
      Console.WriteLine(" Level2Method exception handler")
      
      ' Display the full call stack at this level.
      Dim st1 As New StackTrace(True)
      Console.WriteLine(" Stack trace for this level: {0}", _
         st1.ToString())
      
      ' Build a stack trace from one frame, skipping the current
      ' frame and using the next frame.
      Dim st2 As New StackTrace(New StackFrame(1, True))
      Console.WriteLine(" Stack trace built with next level frame: {0}", _
          st2.ToString())
      
      ' Build a stack trace skipping the current frame, and
      ' including all the other frames.
      Dim st3 As New StackTrace(1, True)
      Console.WriteLine(" Stack trace built from the next level up: {0}", _
          st3.ToString())
      
      Console.WriteLine()
      Console.WriteLine("   ... throwing exception to next level ...")
      Console.WriteLine("-------------------------------------------------")
      Console.WriteLine()
      Throw e
   End Try
End Sub

Observações

Se o número de frames a saltar for maior ou igual ao número total de frames na pilha de chamadas no momento em que a instância é criada, não StackTrace conterão frames.

Aplica-se a

StackTrace(Thread, Boolean)

Atenção

This constructor has been deprecated. Please use a constructor that does not require a Thread parameter. http://go.microsoft.com/fwlink/?linkid=14202

Inicializa uma nova instância da StackTrace classe para um thread específico, capturando opcionalmente a informação da fonte.

Não use esta sobrecarga de construtores.

public:
 StackTrace(System::Threading::Thread ^ targetThread, bool needFileInfo);
public StackTrace(System.Threading.Thread targetThread, bool needFileInfo);
[System.Obsolete("This constructor has been deprecated.  Please use a constructor that does not require a Thread parameter.  http://go.microsoft.com/fwlink/?linkid=14202")]
public StackTrace(System.Threading.Thread targetThread, bool needFileInfo);
new System.Diagnostics.StackTrace : System.Threading.Thread * bool -> System.Diagnostics.StackTrace
[<System.Obsolete("This constructor has been deprecated.  Please use a constructor that does not require a Thread parameter.  http://go.microsoft.com/fwlink/?linkid=14202")>]
new System.Diagnostics.StackTrace : System.Threading.Thread * bool -> System.Diagnostics.StackTrace
Public Sub New (targetThread As Thread, needFileInfo As Boolean)

Parâmetros

targetThread
Thread

O thread cujo rastreio de stack é solicitado.

needFileInfo
Boolean

true para capturar o nome do ficheiro, número da linha e número da coluna; caso contrário, false.

Atributos

Exceções

O tópico targetThread não está suspenso.

Observações

Importante

Não use este construtor. Está obsoleto e não há alternativa recomendada. Quando suspendes um thread, não tens forma de saber que código está a executar, e bloqueios podem ocorrer muito facilmente. Por exemplo, se suspender uma thread enquanto ela mantém bloqueios durante uma avaliação de permissões de segurança, outras threads na AppDomain thread podem ser bloqueadas. Se suspender um thread enquanto está a executar um construtor de classe, outros threads AppDomain que tentam usar essa classe são bloqueados.

Ver também

Aplica-se a

StackTrace(Exception, Int32, Boolean)

Inicializa uma nova instância da StackTrace classe usando o objeto exceção fornecido, saltando o número especificado de frames e capturando opcionalmente a informação da fonte.

public:
 StackTrace(Exception ^ e, int skipFrames, bool fNeedFileInfo);
public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo);
new System.Diagnostics.StackTrace : Exception * int * bool -> System.Diagnostics.StackTrace
Public Sub New (e As Exception, skipFrames As Integer, fNeedFileInfo As Boolean)

Parâmetros

e
Exception

O objeto exceção a partir do qual construir o traço de pilha.

skipFrames
Int32

O número de frames na pilha a partir do qual se deve iniciar o rastreio.

fNeedFileInfo
Boolean

true para capturar o nome do ficheiro, número da linha e número da coluna; caso contrário, false.

Exceções

O parâmetro e é null.

O skipFrames parâmetro é negativo.

Observações

O traço de pilha resultante descreve a pilha no momento da exceção.

Se o número de frames a saltar for maior ou igual ao número total de frames na pilha de chamadas no momento em que a instância é criada, não StackTrace conterão frames.

Ver também

Aplica-se a

StackTrace(Exception, Boolean)

Inicializa uma nova instância da StackTrace classe, usando o objeto de exceção fornecido e opcionalmente capturando a informação da fonte.

public:
 StackTrace(Exception ^ exception, bool needFileInfo);
public:
 StackTrace(Exception ^ e, bool fNeedFileInfo);
public StackTrace(Exception exception, bool needFileInfo);
public StackTrace(Exception e, bool fNeedFileInfo);
new System.Diagnostics.StackTrace : Exception * bool -> System.Diagnostics.StackTrace
new System.Diagnostics.StackTrace : Exception * bool -> System.Diagnostics.StackTrace
Public Sub New (exception As Exception, needFileInfo As Boolean)
Public Sub New (e As Exception, fNeedFileInfo As Boolean)

Parâmetros

exceptione
Exception

O objeto exceção a partir do qual construir o traço de pilha.

needFileInfofNeedFileInfo
Boolean

true para capturar o nome do ficheiro, número da linha e número da coluna; caso contrário, false.

Exceções

O parâmetro e é null.

Observações

O traço de pilha resultante descreve a pilha no momento da exceção.

Ver também

Aplica-se a