먼저 스레드를 만들고 시작하십시오 -
// 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!