C# 程序终止线程


首先创建并启动一个线程 −

// new thread
Thread thread = new Thread(c.display);
thread.Start();

现在显示线程并设置一个停止函数来停止线程工作 −

public void display() {
   while (!flag) {
      Console.WriteLine("It's Working");
      Thread.Sleep(2000);
   }
}
public void Stop() {
   flag = true;
   }
}

示例

下面是使用 C# 终止线程的完整代码。

实时演示

using System;
using System.Threading.Tasks;
using System.Threading;
class Demo {    
   static void Main(string[] args){
      MyClass c = new MyClass();      
      // new thread      
      Thread thread = new Thread(c.display);      
      thread.Start();      
      Console.WriteLine("Press any key to exit!");      
      Console.ReadKey();      
      c.Stop();      
       thread.Join();    
   }
}
public class MyClass {    
   private bool flag = false;    
   public void display() {      
      while (!flag) {        
         Console.WriteLine("It's Working");    
         Thread.Sleep(2000);      
       }    .
   }    .
   public void Stop() {      
      flag = true;    
   }
}

输出

It's Working
Press any key to exit!

更新时间: 2020 年 6 月 19 日

864 次观看

开启您的事业

通过完成课程获得认证

开始
广告
© . All rights reserved.