Thread.Interrupt Method ()


Interrupts a thread that is in the WaitSleepJoin thread state.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
public void Interrupt()

Exception Condition

The caller does not have the appropriate SecurityPermission.

If this thread is not currently blocked in a wait, sleep, or join state, it will be interrupted when it next begins to block.

ThreadInterruptedException is thrown in the interrupted thread, but not until the thread blocks. If the thread never blocks, the exception is never thrown, and thus the thread might complete without ever being interrupted.

The following code example shows the behavior of a running thread when it is interrupted and subsequently gets blocked.

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));

        // The following line causes an exception to be thrown 
        // in ThreadMethod if newThread is currently blocked
        // or becomes blocked in the future.
        Console.WriteLine("Main thread calls Interrupt on newThread.");

        // Tell newThread to go to sleep.
        stayAwake.SleepSwitch = true;

        // Wait for newThread to end.

class StayAwake
    bool sleepSwitch = false;

    public bool SleepSwitch
        set{ sleepSwitch = value; }

    public StayAwake(){}

    public void ThreadMethod()
        Console.WriteLine("newThread is executing ThreadMethod.");
            // Use SpinWait instead of Sleep to demonstrate the 
            // effect of calling Interrupt on a running thread.
            Console.WriteLine("newThread going to sleep.");

            // When newThread goes to sleep, it is immediately 
            // woken up by a ThreadInterruptedException.
        catch(ThreadInterruptedException e)
            Console.WriteLine("newThread cannot go to sleep - " +
                "interrupted by main thread.");


for advanced operations on threads. Associated enumeration: SecurityPermissionFlag.ControlThread.

.NET Framework
Available since 1.1
Return to top