首先创建一个线程并启动它-
//新线程 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(); //新线程 Thread thread = new Thread(c.display); thread.Start(); Console.WriteLine("按任何一个键退出!"); 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 按任何一个键退出!