Alternative of thread.Abort() in Asp.net Core?

纵然是瞬间 提交于 2021-01-29 07:28:41

问题


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 Cancel Task using CancellationToken approach.



来源:https://stackoverflow.com/questions/54554400/alternative-of-thread-abort-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!