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!
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP