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();
}
}
}
}
C#多線程編程實例 線程與窗體交互源碼下載:
------------------------------------------分割線------------------------------------------
免費下載地址在 http://linux.linuxidc.com/
用戶名與密碼都是www.linuxidc.com
具體下載目錄在 /2014年資料/7月/17日/C#多線程編程實例 線程與窗體交互【附源碼】
下載方法見 http://www.linuxidc.com/Linux/2013-07/87684.htm
------------------------------------------分割線------------------------------------------