ThreadInterruptedException Clase

Definición

Excepción que se produce cuando se interrumpe mientras Thread se encuentra en un 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
Herencia
ThreadInterruptedException
Atributos

Ejemplos

En el ejemplo de código siguiente se muestra el comportamiento de un subproceso en ejecución cuando se interrumpe y, posteriormente, se bloquea.

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

Comentarios

Después de crear un subproceso, se encuentra en uno o varios ThreadState estados hasta que se destruye. Al llamar a Interrupt cuando un subproceso está en estado WaitSleepJoin , se producirá un ThreadInterruptedException error en el subproceso de destino. Si el subproceso no está en estado WaitSleepJoin , la excepción no se produce hasta que el subproceso entra en ese estado. Si el subproceso nunca se bloquea, puede finalizar sin ser interrumpido.

ThreadInterruptedException usa el COR_E_THREADINTERRUPTED HRESULT, que tiene el valor 0x80131519.

Para obtener una lista de valores de propiedad iniciales para una instancia de ThreadInterruptedException, vea los ThreadInterruptedException constructores.

Constructores

Nombre Description
ThreadInterruptedException()

Inicializa una nueva instancia de la ThreadInterruptedException clase con propiedades predeterminadas.

ThreadInterruptedException(SerializationInfo, StreamingContext)

Inicializa una nueva instancia de la ThreadInterruptedException clase con datos serializados.

ThreadInterruptedException(String, Exception)

Inicializa una nueva instancia de la ThreadInterruptedException clase con un mensaje de error especificado y una referencia a la excepción interna que es la causa de esta excepción.

ThreadInterruptedException(String)

Inicializa una nueva instancia de la ThreadInterruptedException clase con un mensaje de error especificado.

Propiedades

Nombre Description
Data

Obtiene una colección de pares clave-valor que proporcionan información adicional definida por el usuario sobre la excepción.

(Heredado de Exception)
HelpLink

Obtiene o establece un vínculo al archivo de ayuda asociado a esta excepción.

(Heredado de Exception)
HResult

Obtiene o establece HRESULT, un valor numérico codificado que se asigna a una excepción específica.

(Heredado de Exception)
InnerException

Obtiene la Exception instancia que provocó la excepción actual.

(Heredado de Exception)
Message

Obtiene un mensaje que describe la excepción actual.

(Heredado de Exception)
Source

Obtiene o establece el nombre de la aplicación o el objeto que provoca el error.

(Heredado de Exception)
StackTrace

Obtiene una representación de cadena de los fotogramas inmediatos en la pila de llamadas.

(Heredado de Exception)
TargetSite

Obtiene el método que produce la excepción actual.

(Heredado de Exception)

Métodos

Nombre Description
Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
GetBaseException()

Cuando se reemplaza en una clase derivada, devuelve la Exception causa principal de una o varias excepciones posteriores.

(Heredado de Exception)
GetHashCode()

Actúa como la función hash predeterminada.

(Heredado de Object)
GetObjectData(SerializationInfo, StreamingContext)

Cuando se reemplaza en una clase derivada, establece con SerializationInfo información sobre la excepción.

(Heredado de Exception)
GetType()

Obtiene el tipo de tiempo de ejecución de la instancia actual.

(Heredado de Exception)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
ToString()

Crea y devuelve una representación de cadena de la excepción actual.

(Heredado de Exception)

Eventos

Nombre Description
SerializeObjectState

Se produce cuando se serializa una excepción para crear un objeto de estado de excepción que contiene datos serializados sobre la excepción.

(Heredado de Exception)

Se aplica a

Consulte también