สร้างเธรดก่อนแล้วเริ่ม -
// 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!