Trước tiên hãy tạo một chuỗi và bắt đầu nó -
// new thread Thread thread = new Thread(c.display); thread.Start();
Bây giờ, hãy hiển thị chuỗi và đặt chức năng dừng để dừng hoạt động của chuỗi -
public void display() {
while (!flag) {
Console.WriteLine("It's Working");
Thread.Sleep(2000);
}
}
public void Stop() {
flag = true;
}
} Ví dụ
Sau đây là mã hoàn chỉnh để tìm hiểu cách hủy một chuỗi trong 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;
}
} Đầu ra
It's Working Press any key to exit!