C# 程序终止线程
csharpserver side programmingprogramming更新于 2025/9/23 21:38:00
首先创建一个线程并启动它 −
// 新线程 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!

