net core 3.0 多线程学习1

问题:net core 3.0不支持 t1.Abort(); 线程终止方法,会报异常。

   异常信息:System.PlatformNotSupportedException:“Thread abort is not supported on this platform.”

static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Thread t1 = new Thread(psleep);
t1.Start();
Thread.Sleep(TimeSpan.FromSeconds(6));
t1.Abort();

}

public static void psleep() {
for (int i = 1; i <= 10; i++)
{
Thread.Sleep(TimeSpan.FromSeconds(2));

Console.WriteLine(i);
}

解决参考:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.threadabortexception?view=netframework-4.8 

然而此参考,不好使。

换方案:参考网友:

既然不不能终止,我们就中断吧:
Interrupt();

例如:

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");
  }
}
}
}

多加个注意:https://www.cnblogs.com/HCCZX/p/11555751.html

1.这是一个 后台线程,IsBackground=true,  主线程完成后,后台子线程也停止了,即使 子线程 还有没运行完,也要停止

2.因为线程IsBackground=false,不是后台线程,所以主线程即使完成了,子线程也会继续完成
————————————————
版权声明:本文为CSDN博主「盗理者」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_36051316/article/details/84172215

猜你喜欢

转载自www.cnblogs.com/wuyues/p/12757892.html
今日推荐