Thread.Abort is obsolete

The Thread.Abort APIs are obsolete. Projects that target .NET 5 or a later version will encounter compile-time warning SYSLIB0006 if these methods are called.

Change description

Previously, calls to Thread.Abort did not produce compile-time warnings, however, the method did throw a PlatformNotSupportedException at run time.

Starting in .NET 5, Thread.Abort is marked obsolete as warning. Calling this method produces compiler warning SYSLIB0006. The implementation of the method is unchanged, and it continues to throw a PlatformNotSupportedException.

Reason for change

Given that Thread.Abort always throws a PlatformNotSupportedException on all .NET implementations except .NET Framework, ObsoleteAttribute was added to the method to draw attention to places where it's called.

When you call Thread.Abort 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. For this reason, Thread.Abort always throws a PlatformNotSupportedException on .NET Core and .NET 5+.

Version introduced

5.0

  • Use a CancellationToken to abort processing of a unit of work instead of calling Thread.Abort. The following example illustrates the use of CancellationToken.

    void ProcessPendingWorkItemsNew(CancellationToken cancellationToken)
    {
        if (QueryIsMoreWorkPending())
        {
            // If the CancellationToken is marked as "needs to cancel",
            // this will throw the appropriate exception.
            cancellationToken.ThrowIfCancellationRequested();
    
            WorkItem work = DequeueWorkItem();
            ProcessWorkItem(work);
        }
    }
    

    For more information, see Cancellation in managed threads.

  • To suppress the compile-time warning, suppress warning code SYSLIB0006. The warning code is specific to Thread.Abort and suppressing it doesn't suppress other obsoletion warnings in your code. However, we recommend that you remove calls to Thread.Abort instead of suppressing the warning.

    void MyMethod()
    {
    #pragma warning disable SYSLIB0006
        Thread.CurrentThread.Abort();
    #pragma warning restore SYSLIB0006
    }
    

    You can also suppress the warning in the project file.

    <PropertyGroup>
      <OutputType>Exe</OutputType>
      <TargetFramework>net5.0</TargetFramework>
      <!-- Disable "Thread.Abort is obsolete" warnings for entire project. -->
      <NoWarn>$(NoWarn);SYSLIB0006</NoWarn>
    </PropertyGroup>
    

Affected APIs