Export (0) Print
Expand All

Thread.Abort Method ()

.NET Framework 1.1

Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.

[Visual Basic]
Overloads Public Sub Abort()
[C#]
public void Abort();
[C++]
public: void Abort();
[JScript]
public function Abort();

Exceptions

Exception Type Condition
SecurityException The caller does not have the required permission.

Remarks

When this method is invoked on a thread, the system throws a ThreadAbortException in the thread to abort it. ThreadAbortException is a special exception that can be caught by application code, but is re-thrown at the end of the catch block unless ResetAbort is called. ResetAbort cancels the request to abort, and prevents the ThreadAbortException from terminating the thread. Unexecuted finally blocks are executed before the thread is aborted.

Note   When a thread calls Abort on itself, the effect is similar to throwing an exception; the ThreadAbortException happens immediately, and the result is predictable. However, if one thread calls Abort on another thread, the abort interrupts whatever code is running. There is a chance the thread could abort while a finally block is running, in which case the finally block is aborted. There is also a chance that a static constructor could be aborted. In rare cases, this might prevent instances of that class from being created in that application domain.

The thread is not guaranteed to abort immediately, or at all. This situation can occur if a thread does an unbounded amount of computation in the finally blocks that are called as part of the abort procedure, thereby indefinitely delaying the abort. To ensure a thread has aborted, invoke a Join method on the thread after calling Abort.

If Abort is called on a thread that has not been started, the thread will abort when Start is called. If Abort is called on a thread that has been suspended, the thread is resumed and then aborted. If Abort is called on a thread that is blocked or is sleeping, the thread is interrupted and then aborted. If, while executing unmanaged code, a thread ignores a ThreadAbortException, the system re-throws the ThreadAbortException when the thread begins executing managed code.

If two calls to Abort come at the same time, it is possible that one call set the state information and the other call executes the Abort. However, an application cannot distinguish this.

After Abort is invoked on a thread, the state of the thread includes AbortRequested. After the thread has terminated as a result of a successful call to Abort, the state of the thread is changed to Stopped. With sufficient permissions, a thread that is the target of an Abort can cancel the abort using the ResetAbort method. For an example that demonstrates calling the ResetAbort method, see the ThreadAbortException class.

Example

[Visual Basic, C#, C++] The following code example demonstrates that a second call to the Abort method causes a thread to terminate inside its finally block if the ResetAbort method was called by the thread in response to the first call to Abort. If ResetAbort was not called, the second call to Abort is ignored.

[Visual Basic] 
Imports Microsoft.VisualBasic
Imports System
Imports System.Threading

Public Class Test

    Shared Sub Main()
    
        Dim firstThread  As Thread = New Thread(AddressOf Test.TestMethod)
        Dim secondThread As Thread = New Thread(AddressOf Test.TestMethod)
        firstThread.Name  = "First "
        secondThread.Name = "Second"
        firstThread.Start()
        secondThread.Start()
        Thread.Sleep(2000)

        ' Abort both threads.
        Console.WriteLine(vbCrLf & "Main aborting both threads.")
        firstThread.Abort()
        secondThread.Abort()
        Thread.Sleep(2000)

        ' Call Abort a second time if the threads have not aborted.
        If (firstThread.ThreadState And _
            (ThreadState.Aborted Or ThreadState.Stopped)) = 0 Then
        
            Console.WriteLine(vbCrLf & "Main aborting first thread." & vbCrLf)
            firstThread.Abort()
        End If
        If (secondThread.ThreadState And _
            (ThreadState.Aborted Or ThreadState.Stopped)) = 0 Then
        
            Console.WriteLine(vbCrLf & "Main aborting second thread." & vbCrLf)
            secondThread.Abort()
        End If

        ' Wait for the threads to terminate.
        firstThread.Join()
        Console.WriteLine(vbCrLf & "First  thread terminated.")
        If secondThread.Join(2000) Then
            Console.WriteLine(vbCrLf & "Second thread terminated.")
        Else
            Console.WriteLine( _
                vbCrLf & "Join timed out - second thread still running.")
        End If
        Console.WriteLine(vbCrLf & "Main exiting.")

    End Sub

    Shared Sub TestMethod()
        Dim threadName As String = Thread.CurrentThread.Name
        Try
            While True
                Console.WriteLine("{0} thread running.", threadName)
                Thread.Sleep(1000)
            End While
        Catch ex As ThreadAbortException
        
            ' Only the first thread calls ResetAbort.
            If(threadName = "First ") Then
                Thread.ResetAbort()
                Console.WriteLine(vbCrLf & "First  thread calling ResetAbort.")
            Else
                Console.WriteLine(vbCrLf & "Second thread not calling ResetAbort.")
            End If
        Finally
            While True
                Console.WriteLine("{0} thread running in " & _
                    "Finally block.", threadName)
                Thread.Sleep(1000)
            End While
        End Try
    End Sub

End Class

[C#] 
using System;
using System.Threading;

class Test
{
    public static void Main()
    {
        Thread firstThread  = new Thread(new ThreadStart(TestMethod));
        Thread secondThread = new Thread(new ThreadStart(TestMethod));
        firstThread.Name  = "First ";
        secondThread.Name = "Second";
        firstThread.Start();
        secondThread.Start();
        Thread.Sleep(2000);

        // Abort both threads.
        Console.WriteLine("\nMain aborting both threads.");
        firstThread.Abort();
        secondThread.Abort();
        Thread.Sleep(2000);

        // Call Abort a second time if the threads have not aborted.
        if((firstThread.ThreadState & 
            (ThreadState.Aborted | ThreadState.Stopped)) == 0)
        {
            Console.WriteLine("\nMain aborting first thread.\n");
            firstThread.Abort();
        }
        if((secondThread.ThreadState & 
            (ThreadState.Aborted | ThreadState.Stopped)) == 0)
        {
            Console.WriteLine("\nMain aborting second thread.\n");
            secondThread.Abort();
        }

        // Wait for the threads to terminate.
        firstThread.Join();
        Console.WriteLine("\nFirst  thread terminated.");
        if(secondThread.Join(2000))
        {
            Console.WriteLine("\nSecond thread terminated.");
        }
        else
        {
            Console.WriteLine(
                "\nJoin timed out - second thread still running.");
        }

        Console.WriteLine("\nMain exiting.");
    }

    static void TestMethod()
    {
        string threadName = Thread.CurrentThread.Name;
        try
        {
            while(true)
            {
                Console.WriteLine("{0} thread running.", threadName);
                Thread.Sleep(1000);
            }
        }
        catch(ThreadAbortException e)
        {
            // Only the first thread calls ResetAbort.
            if(threadName == "First ")
            {
                Thread.ResetAbort();
            }
            Console.WriteLine("\n{0} thread {1}calling ResetAbort.", 
                threadName, threadName == "First " ? "" : "not ");
        }
        finally
        {
            while(true)
            {
                Console.WriteLine("{0} thread running in " +
                    "finally block.", threadName);
                Thread.Sleep(1000);
            }
        }
    }
}

[C++] 
#using <mscorlib.dll>
using namespace System;
using namespace System::Threading;

__gc class Test
{
    Test() {}
public:
    static void TestMethod()
    {
        String* threadName = Thread::CurrentThread->Name;
        try
        {
            while(true)
            {
                Console::WriteLine(S"{0} thread running.", 
                    threadName);
                Thread::Sleep(1000);
            }
        }
        catch(ThreadAbortException* e)
        {
            // Only the first thread calls ResetAbort.
            if(threadName == S"First ")
            {
                Thread::ResetAbort();
            }
            Console::WriteLine(S"\n{0} thread {1}calling ResetAbort.",
                threadName, threadName == S"First " ? S"" : S"not ");
        }
        __finally
        {
            while(true)
            {
                Console::WriteLine(S"{0} thread running in "
                    S"finally block.", threadName);
                Thread::Sleep(1000);
            }
        }
    }
};

void main()
{
    Thread* firstThread  = 
        new Thread(new ThreadStart(0, &Test::TestMethod));
    Thread* secondThread = 
        new Thread(new ThreadStart(0, &Test::TestMethod));
    firstThread->Name  = S"First ";
    secondThread->Name = S"Second";
    firstThread->Start();
    secondThread->Start();
    Thread::Sleep(2000);

    // Abort both threads.
    Console::WriteLine(S"\nMain aborting both threads.");
    firstThread->Abort();
    secondThread->Abort();
    Thread::Sleep(2000);

    // Call Abort a second time if the threads have not aborted.
    if((firstThread->ThreadState & 
        (ThreadState::Aborted | ThreadState::Stopped)) == 0)
    {
        Console::WriteLine(S"\nMain aborting first thread.\n");
        firstThread->Abort();
    }
    if((secondThread->ThreadState & 
        (ThreadState::Aborted | ThreadState::Stopped)) == 0)
    {
        Console::WriteLine(S"\nMain aborting second thread.\n");
        secondThread->Abort();
    }

    // Wait for the threads to terminate.
    firstThread->Join();
    Console::WriteLine(S"\nFirst  thread terminated.");
    if(secondThread->Join(2000))
    {
        Console::WriteLine(S"\nSecond thread terminated.");
    }
    else
    {
        Console::WriteLine(
            S"\nJoin timed out - second thread still running.");
    }

    Console::WriteLine(S"\nMain exiting.");
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, Common Language Infrastructure (CLI) Standard

.NET Framework Security: 

See Also

Thread Class | Thread Members | System.Threading Namespace | Thread.Abort Overload List | ThreadAbortException | Aborted | AbortRequested | Threads and Threading | Using Threads and Threading | Destroying Threads

Show:
© 2014 Microsoft