摘要:[C#] Thread 基本應用
參考:
技術文章:ConsoleKeyInfo 結構 Thread 類別
水瓶大,做了一個 Console 的版本,我自己做了一個 WindowForm 的版本練習,
技術文章:Delegate 類別 Control.Invoke 方法
using System.Threading;
namespace InfiniteLoop_2_ {
public partial class Form1 : Form {
//宣告執行緒類別變數
private Thread thread;
//定義委派型別
delegate void SampleDge(int i);
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
//建立執行緒物件
thread = new Thread(new ThreadStart(startThread));
thread.Start();
}
private void startThread() {
int i = 0;
//建立委派物件
SampleDge d1 = new SampleDge(ShowText);
while (true) {
//使用視窗代碼的執行緒存取表單上的控制項。
this.Invoke(d1, i);
i++;
}
}
private void ShowText(int Number) {
this.textBox1.Text = Number.ToString();
}
//覆寫處理對話方塊按鍵函式
protected override bool ProcessDialogKey(Keys keyData) {
//判斷是否按下 ESC
if (keyData == Keys.Escape) {
//關閉執行緒物件
thread.Abort();
}
return true;
}
//覆寫表單正在關閉函式
protected override void OnFormClosing(FormClosingEventArgs e) {
if (thread.ThreadState != ThreadState.Stopped) {
thread.Abort();
}
}
}
}歡迎指教
附上程式碼:InfiniteLoop(2).rar
三小俠 小弟獻醜,歡迎指教