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