dotnet core equivalent to Thread.Abort dotnet core equivalent to Thread.Abort multithreading multithreading

dotnet core equivalent to Thread.Abort


Use thread.Interrupt(); instead of Abort method.


Without aborting the only solution is to poll the cancellation request often enough so after all the while (!canceled) solution you mentioned.

The examples I saw are using while (!canceled) loops, which cant stop long operations (like Thread.Sleep(1000000).

This is just partially true. For example, this can be re-written like this to be responsive:

 var timeout = TimeSpan.FromSeconds(60); var stopwatch = new Stopwatch(); stopwatch.Start(); while (!cancelToken.IsCancellationRequested  && stopwatch.ElapsedMilliseconds < timeout){    Thread.Sleep(10);}

Of course, not every task can be easily re-written to poll the cancellation like this. If you are in a deep call chain it can be a pain to check the cancellation at every level. For that reason you can also use the CancellationToken.ThrowIfCancellationRequested method, which will throw an OperationCanceledException if there was a cancel request. I usually tend to not throwing an exception just for myself and using it for control flow but cancellation is one of the areas where it can be justified.

This is solution has of course some limitations compared to Abort:

  • You will not able to cancel 3rd party routines, which don't support cancellation and you cannot refactor them
  • The OperationCanceledException can be swallowed easily, whereas ThreadAbortException was always re-raised at the end of the catch blocks so a 3rd part library could be aborted by a good chance even if contained general catch blocks.

Update:

If you are confident/desperate enough you can use the ThreadEx.Abort method, which calls the Thread.AbortInternal by reflection. Though it is not guaranteed it will be a long-living solution in .NET Core.

Though I don't completely agree with making Thread.Abort obsolete as it was a good last-chance tool for shutting down routines on which you didn't have influence otherwise, I'm also at the side abortion must be avoided at all costs as it can have nasty side effects. If you are the author of the whole code base it can be always avoided.

Update 2:

It seems that AbortInternal has been removed since then. At least current .NET Core source does not contain such a method.