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