C#多線程編程執行個體 線程與表單互動
代碼:
public partial class Form1 : Form { //聲明線程數組 Thread[] workThreads = new Thread[10]; public Form1() { InitializeComponent(); } //此委託允許非同步調用為Listbox添加Item delegate void AddItemCallback(string text); //這種方法示範如何線上程安全的模式下調用Windows表單上的控制項。 private void AddItem(string text) { if (this.listBox1.InvokeRequired) { AddItemCallback d = new AddItemCallback(AddItem); this.Invoke(d, new object[] { text }); } else { this.listBox1.Items.Add(text); } } //資料擷取方法 public void DataGet() { while (true) { AddItem("ok"); Thread.Sleep(1000); } //如果此方法退出了,那麼這個線程也就退出了 } /// <summary> /// 啟動線程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //迴圈建立並啟動線程執行 for (int i = 0; i < workThreads.Length; i++) { if (workThreads[i] == null) { //如果線程不存在,則建立 workThreads[i] = new Thread(new ThreadStart(DataGet)); workThreads[i].Name = i.ToString(); workThreads[i].Start(); } else { //已經存在,如果沒有運行,則啟動 if (workThreads[i].ThreadState == ThreadState.Aborted || workThreads[i].ThreadState == ThreadState.Stopped) { workThreads[i] = new Thread(new ThreadStart(DataGet)); workThreads[i].Name = i.ToString(); workThreads[i].Start(); }else{ workThreads[i].Start(); } } } } /// <summary> /// 停止線程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { //迴圈停止線程執行 for (int i = 0; i < workThreads.Length; i++) { //如果線程存在,並且狀態不是停止也不是終止的,則終止該線程 if (workThreads[i] != null && workThreads[i].ThreadState != ThreadState.Stopped && workThreads[i].ThreadState != ThreadState.Aborted) { workThreads[i].Abort(); } } }