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!

更新時間: 2020 年 6 月 19 日

864 次觀看

開啟您的事業

透過完成課程獲得認證

開始
廣告