ThreadInterruptedException Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
A exceção que é lançada quando a Thread é interrompido enquanto está em estado de espera.
public ref class ThreadInterruptedException : SystemException
[System.Serializable]
public class ThreadInterruptedException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ThreadInterruptedException : SystemException
public class ThreadInterruptedException : SystemException
[<System.Serializable>]
type ThreadInterruptedException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ThreadInterruptedException = class
inherit SystemException
type ThreadInterruptedException = class
inherit SystemException
Public Class ThreadInterruptedException
Inherits SystemException
- Herança
- Atributos
Exemplos
O exemplo de código seguinte mostra o comportamento de um thread em execução quando é interrompido e, subsequentemente, bloqueado.
using System;
using System.Security.Permissions;
using System.Threading;
class ThreadInterrupt
{
static void Main()
{
StayAwake stayAwake = new StayAwake();
Thread newThread =
new Thread(new ThreadStart(stayAwake.ThreadMethod));
newThread.Start();
// The following line causes an exception to be thrown
// in ThreadMethod if newThread is currently blocked
// or becomes blocked in the future.
newThread.Interrupt();
Console.WriteLine("Main thread calls Interrupt on newThread.");
// Tell newThread to go to sleep.
stayAwake.SleepSwitch = true;
// Wait for newThread to end.
newThread.Join();
}
}
class StayAwake
{
bool sleepSwitch = false;
public bool SleepSwitch
{
set{ sleepSwitch = value; }
}
public StayAwake(){}
public void ThreadMethod()
{
Console.WriteLine("newThread is executing ThreadMethod.");
while(!sleepSwitch)
{
// Use SpinWait instead of Sleep to demonstrate the
// effect of calling Interrupt on a running thread.
Thread.SpinWait(10000000);
}
try
{
Console.WriteLine("newThread going to sleep.");
// When newThread goes to sleep, it is immediately
// woken up by a ThreadInterruptedException.
Thread.Sleep(Timeout.Infinite);
}
catch(ThreadInterruptedException e)
{
Console.WriteLine("newThread cannot go to sleep - " +
"interrupted by main thread.");
}
}
}
Option Explicit
Option Strict
Imports System.Security.Permissions
Imports System.Threading
Public Class ThreadInterrupt
<MTAThread> _
Shared Sub Main()
Dim stayAwake As New StayAwake()
Dim newThread As New Thread(AddressOf stayAwake.ThreadMethod)
newThread.Start()
' The following line causes an exception to be thrown
' in ThreadMethod if newThread is currently blocked
' or becomes blocked in the future.
newThread.Interrupt()
Console.WriteLine("Main thread calls Interrupt on newThread.")
' Tell newThread to go to sleep.
stayAwake.SleepSwitch = True
' Wait for newThread to end.
newThread.Join()
End Sub
End Class
Public Class StayAwake
Dim sleepSwitchValue As Boolean = False
WriteOnly Property SleepSwitch As Boolean
Set
sleepSwitchValue = Value
End Set
End Property
Sub New()
End Sub
Sub ThreadMethod()
Console.WriteLine("newThread is executing ThreadMethod.")
While Not sleepSwitchValue
' Use SpinWait instead of Sleep to demonstrate the
' effect of calling Interrupt on a running thread.
Thread.SpinWait(10000000)
End While
Try
Console.WriteLine("newThread going to sleep.")
' When newThread goes to sleep, it is immediately
' woken up by a ThreadInterruptedException.
Thread.Sleep(Timeout.Infinite)
Catch ex As ThreadInterruptedException
Console.WriteLine("newThread cannot go to " & _
"sleep - interrupted by main thread.")
End Try
End Sub
End Class
Observações
Depois de um fio ser criado, ele permanece em um ou mais ThreadState estados até ser destruído. Chamar Interrupt quando uma thread está nesse WaitSleepJoin estado fará com que a ThreadInterruptedException seja lançado na thread de destino. Se a thread não estiver nesse WaitSleepJoin estado, a exceção não é lançada até que a thread entre nesse estado. Se a linha de execução nunca bloquear, pode concluir-se sem nunca ser interrompida.
ThreadInterruptedException usa o COR_E_THREADINTERRUPTED HRESULT, que tem o valor 0x80131519.
Para obter uma lista dos valores iniciais de propriedade de uma instância de ThreadInterruptedException, consulte os construtores de ThreadInterruptedException.
Construtores
| Name | Description |
|---|---|
| ThreadInterruptedException() |
Inicializa uma nova instância da ThreadInterruptedException classe com propriedades por defeito. |
| ThreadInterruptedException(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da ThreadInterruptedException classe com dados serializados. |
| ThreadInterruptedException(String, Exception) |
Inicializa uma nova instância da ThreadInterruptedException classe com uma mensagem de erro especificada e uma referência à exceção interna que é a causa dessa exceção. |
| ThreadInterruptedException(String) |
Inicializa uma nova instância da ThreadInterruptedException classe com uma mensagem de erro especificada. |
Propriedades
| Name | Description |
|---|---|
| Data |
Obtém uma coleção de pares chave/valor que fornecem informação adicional definida pelo utilizador sobre a exceção. (Herdado de Exception) |
| HelpLink |
Obtém ou define um link para o ficheiro de ajuda associado a esta exceção. (Herdado de Exception) |
| HResult |
Recebe ou define HRESULT, um valor numérico codificado atribuído a uma exceção específica. (Herdado de Exception) |
| InnerException |
Obtém a Exception instância que causou a exceção atual. (Herdado de Exception) |
| Message |
Recebe uma mensagem que descreve a exceção atual. (Herdado de Exception) |
| Source |
Obtém ou define o nome do aplicativo ou o objeto que causa o erro. (Herdado de Exception) |
| StackTrace |
Obtém uma representação string dos frames imediatos na stack de chamadas. (Herdado de Exception) |
| TargetSite |
Obtém o método que lança a exceção atual. (Herdado de Exception) |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetBaseException() |
Quando sobrescrito numa classe derivada, devolve o Exception que é a causa raiz de uma ou mais exceções subsequentes. (Herdado de Exception) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Quando sobreposto numa classe derivada, define a SerializationInfo informação com sobre a exceção. (Herdado de Exception) |
| GetType() |
Obtém o tipo de execução da instância atual. (Herdado de Exception) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Cria e devolve uma representação string da exceção atual. (Herdado de Exception) |
evento
| Name | Description |
|---|---|
| SerializeObjectState |
Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção. (Herdado de Exception) |