In the past I used to start a new thread for sorting, and abort it when the user clicked 'Cancel', and it worked flawlessly on virtually all .NET Framework versions.
But since the introduction of .NET Core and .NET 5+, a call to Thread.Abort()
throws PlatformNotSupportedException
.
So it is time now to find a better way to do that. The main problem is that Array.Sort()
and List.Sort()
methods do not acccept a CancellationToken
.
I could go by sending my own Comparison
delegate and call cancellationToken.ThrowIfCancellationRequested();
inside but that would have a significant performance impact.
How to properly cancel an in-place sort without sacrificing much performance in newer dotnet versions?
Attached a snippet that used to work on .NET Framework:
byte[] arr = new byte[1024 * 1024 * 1024];
Thread thread = new Thread(() => Array.Sort(arr));
thread.IsBackground = true;
thread.Start();
if (!thread.Join(1000))
thread.Abort();