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); } //如果此方法退出了,那麼這個線程也就退出了 } ////// 啟動線程 /// /// /// 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(); } } } } ////// 停止線程 /// /// /// 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(); } } } }