dotnetCore 线程中断问题

版权声明:版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/qq_36051316/article/details/84172215

dotnetCore 线程终止问题,我们用中断解决


不想看废话的直接用这个方法:Interrupt();
链接:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread.interrupt?view=netcore-2.1#System_Threading_Thread_Interrupt


在今天我使用dotnetcore多线程的时候,发现一个问题。
Thread居然没有Abort() 方法。
看下图: 仅限.NET Core 不支持此成员。。。。。。,六个句号献给真香。
ABORT
那么很多小伙伴还要用终止怎么办呢?
既然不不能终止,我们就中断吧:
dangdangdangdangdangdang
:
Interrupt();
使用截图如下:(执行6秒就中断的截图)
执行6秒就中断的截图

官方参考方法
https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread.interrupt?view=netcore-2.1#System_Threading_Thread_Interrupt

后面的就交给后台自己释放了。
记得加上

   thread.IsBackground=true;

现在交出完整核心代码:

using System;
using System.Threading;
namespace dotnetcoreThreadInterrupt
{
    class Application
    {
        public void Start()
        {
            Thread thread = new Thread(TtoRun);
            thread.IsBackground=true;
            thread.Start();
            for (int i = 0; i < 6; i++)
            {
                Thread.Sleep(1000);
            }
            thread.Interrupt();
        }
        public void TtoRun()
        {
            while (true)
            {
                Thread.Sleep(1000);
                System.Console.WriteLine("W");
            }
        }
    }
}

Gitbub链接: https://github.com/daolizhe/dotnetcoreThreadDemo

Github链接截图

执行结果:记住是目录dotnetcoreThreadInterrupt直接dotnet run就能用,如果版本不对,改个版本
执行结果

猜你喜欢

转载自blog.csdn.net/qq_36051316/article/details/84172215
今日推荐