Upraviť

Zdieľať cez


Thread.Abort Method

Definition

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

Overloads

Abort()
Obsolete.

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.

Abort(Object)
Obsolete.

Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread while also providing exception information about the thread termination. Calling this method usually terminates the thread.

Remarks

Important

Use the Thread.Abort method with caution. Particularly when you call it to abort a thread other than the current thread, you don't know what code has executed or failed to execute when the ThreadAbortException is thrown. You also cannot be certain of the state of your application or any application and user state that it's responsible for preserving. For example, calling Thread.Abort may prevent the execution of static constructors or the release of managed or unmanaged resources.

Abort()

Source:
Thread.cs
Source:
Thread.cs
Source:
Thread.cs

Caution

Thread.Abort is not supported and throws PlatformNotSupportedException.

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.

public:
 void Abort();
[System.Obsolete("Thread.Abort is not supported and throws PlatformNotSupportedException.", DiagnosticId="SYSLIB0006", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public void Abort ();
public void Abort ();
[<System.Obsolete("Thread.Abort is not supported and throws PlatformNotSupportedException.", DiagnosticId="SYSLIB0006", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
member this.Abort : unit -> unit
member this.Abort : unit -> unit
Public Sub Abort ()
Attributes

Exceptions

.NET Core and .NET 5+ only: In all cases.

The caller does not have the required permission.

The thread that is being aborted is currently suspended.

Remarks

This method is obsolete. On .NET 5 and later versions, calling this method produces a compile-time warning. This method throws a PlatformNotSupportedException at run time on .NET 5 and later and .NET Core.

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 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 wait until a thread has aborted, you can call the Join method on the thread after calling the Abort method, but there is no guarantee the wait will end.

Note

The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region. If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur.

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 is blocked or is sleeping, the thread is interrupted and then aborted.

If Abort is called on a thread that has been suspended, a ThreadStateException is thrown in the thread that called Abort, and AbortRequested is added to the ThreadState property of the thread being aborted. A ThreadAbortException is not thrown in the suspended thread until Resume is called.

If Abort is called on a managed thread while it is executing unmanaged code, a ThreadAbortException is not thrown until the thread returns to managed code.

If two calls to Abort come at the same time, it is possible for one call to set the state information and the other call to execute the Abort. However, an application cannot detect this situation.

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.

See also

Applies to

Abort(Object)

Source:
Thread.cs
Source:
Thread.cs
Source:
Thread.cs

Caution

Thread.Abort is not supported and throws PlatformNotSupportedException.

Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread while also providing exception information about the thread termination. Calling this method usually terminates the thread.

public:
 void Abort(System::Object ^ stateInfo);
[System.Obsolete("Thread.Abort is not supported and throws PlatformNotSupportedException.", DiagnosticId="SYSLIB0006", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public void Abort (object? stateInfo);
public void Abort (object stateInfo);
public void Abort (object? stateInfo);
[<System.Obsolete("Thread.Abort is not supported and throws PlatformNotSupportedException.", DiagnosticId="SYSLIB0006", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
member this.Abort : obj -> unit
member this.Abort : obj -> unit
Public Sub Abort (stateInfo As Object)

Parameters

stateInfo
Object

An object that contains application-specific information, such as state, which can be used by the thread being aborted.

Attributes

Exceptions

.NET Core and .NET 5+ only: In all cases.

The caller does not have the required permission.

The thread that is being aborted is currently suspended.

Examples

The following code example shows how to pass information to a thread that is being aborted.

using namespace System;
using namespace System::Threading;
ref class Test
{
private:
   Test(){}


public:
   static void TestMethod()
   {
      try
      {
         while ( true )
         {
            Console::WriteLine( "New thread running." );
            Thread::Sleep( 1000 );
         }
      }
      catch ( ThreadAbortException^ abortException ) 
      {
         Console::WriteLine( dynamic_cast<String^>(abortException->ExceptionState) );
      }

   }

};

int main()
{
   Thread^ newThread = gcnew Thread( gcnew ThreadStart( &Test::TestMethod ) );
   newThread->Start();
   Thread::Sleep( 1000 );
   
   // Abort newThread.
   Console::WriteLine( "Main aborting new thread." );
   newThread->Abort( "Information from main." );
   
   // Wait for the thread to terminate.
   newThread->Join();
   Console::WriteLine( "New thread terminated - main exiting." );
}
using System;
using System.Threading;

class Test
{
    public static void Main()
    {
        Thread newThread  = new Thread(new ThreadStart(TestMethod));
        newThread.Start();
        Thread.Sleep(1000);

        // Abort newThread.
        Console.WriteLine("Main aborting new thread.");
        newThread.Abort("Information from Main.");

        // Wait for the thread to terminate.
        newThread.Join();
        Console.WriteLine("New thread terminated - Main exiting.");
    }

    static void TestMethod()
    {
        try
        {
            while(true)
            {
                Console.WriteLine("New thread running.");
                Thread.Sleep(1000);
            }
        }
        catch(ThreadAbortException abortException)
        {
            Console.WriteLine((string)abortException.ExceptionState);
        }
    }
}
open System.Threading

let testMethod () =
    try
        while true do
            printfn "New thread running."
            Thread.Sleep 1000
    with :? ThreadAbortException as abortException ->
        printfn $"{abortException.ExceptionState :?> string}"

let newThread = Thread testMethod
newThread.Start()
Thread.Sleep 1000

// Abort newThread.
printfn "Main aborting new thread."
newThread.Abort "Information from Main."

// Wait for the thread to terminate.
newThread.Join()
printfn "New thread terminated - Main exiting."
Imports System.Threading

Public Class Test

    <MTAThread> _
    Shared Sub Main()
        Dim newThread As New Thread(AddressOf TestMethod)
        newThread.Start()
        Thread.Sleep(1000)

        ' Abort newThread.
        Console.WriteLine("Main aborting new thread.")
        newThread.Abort("Information from Main.")

        ' Wait for the thread to terminate.
        newThread.Join()
        Console.WriteLine("New thread terminated - Main exiting.")
    End Sub

    Shared Sub TestMethod()
        Try
            While True
                Console.WriteLine("New thread running.")
                Thread.Sleep(1000)
            End While
        Catch abortException As ThreadAbortException
            Console.WriteLine( _
                CType(abortException.ExceptionState, String))
        End Try
    End Sub

End Class

Remarks

This method is obsolete. On .NET 5 and later versions, calling this method produces a compile-time warning. This method throws a PlatformNotSupportedException at run time on .NET 5 and later and .NET Core.

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 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 wait until a thread has aborted, you can call the Join method on the thread after calling the Abort method, but there is no guarantee that the wait will end.

Note

The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region. If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur.

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 is blocked or is sleeping, the thread is interrupted and then aborted.

If Abort is called on a thread that has been suspended, a ThreadStateException is thrown in the thread that called Abort, and AbortRequested is added to the ThreadState property of the thread being aborted. A ThreadAbortException is not thrown in the suspended thread until Resume is called.

If Abort is called on a managed thread while it is executing unmanaged code, a ThreadAbortException is not thrown until the thread returns to managed code.

If two calls to Abort come at the same time, it is possible for one call to set the state information and the other call to execute the Abort. However, an application cannot detect this situation.

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.

See also

Applies to