问题
Is there any alternative option for thread.Abort() in asp.net core as it no longer support with .Core.
// Exceptions:
// T:System.PlatformNotSupportedException:
// .NET Core only: This member is not supported.
This is throw PlatformNotSupportedException exception.
I used thread.Interrupt() but it not work as per expectation.
回答1:
Thread.Abort()
has been removed, since it could not be reliably ported to all platforms and in general poses a threat to the entire app domain, when used incorrectly.
The recommended way (especially for ASP.NET Core) is now to use Tasks and "abort" them with CancellationTokens. You can learn more about how to use CancellationTokens here.
回答2:
A solution here could be to use a shared variable which unless set to false
will allow the thread to continue, like tickRunning
to control the loop in the below code example:
using System;
using System.Threading;
namespace SharedFlagVariable
{
class Program
{
static volatile bool tickRunning; // flag variable
static void Main(string[] args)
{
tickRunning = true;
Thread tickThread = new Thread(() =>
{
while (tickRunning)
{
Console.WriteLine("Tick");
Thread.Sleep(1000);
}
});
tickThread.Start();
Console.WriteLine("Press a key to stop the clock");
Console.ReadKey();
tickRunning = false;
Console.WriteLine("Press a key to exit");
Console.ReadKey();
}
}
}
P.S. If you prefer to use
System.Threading.Task
library then check out this post explaining how to CancelTask
using CancellationToken approach.
来源:https://stackoverflow.com/questions/54554400/alternative-of-thread-abort-in-asp-net-core