摘要:多執行緒設定控制項
private void button8_Click(object sender, EventArgs e)
{
//取得目前執行緒ID
MessageBox.Show(Thread.CurrentThread.ManagedThreadId.ToString());
//透過非同步方法取得主機
Dns.BeginGetHostAddresses(this.textBox1.Text, new AsyncCallback(getAddressList), null);
}
private void getAddressList(IAsyncResult iar)
{
string str = "";
if (iar.IsCompleted)
{
//解析主機名稱
IPHostEntry iphe = Dns.Resolve(this.textBox1.Text);
foreach (IPAddress ipa in iphe.AddressList)
{
str += ipa + Environment.NewLine + " = " + Thread.CurrentThread.ManagedThreadId;
}
}
this.setText(str);
}
//委派物件傳入參數型態須與指定之方法的傳入參數相同型態
private delegate void AddIPCallback(string str);
private void setText(string str)
{
//確認建立控制項的執行緒與目前執行緒是否相同,不同則True,反之
if (this.textBox2.InvokeRequired)
{
//傳入委派物件,第二參數為setText的傳入參數
this.textBox2.Invoke(new AddIPCallback(setText), str + " = " + Thread.CurrentThread.ManagedThreadId);
}
else
{
this.textBox2.Text = str + " = " + Thread.CurrentThread.ManagedThreadId;
}
}
參考:https://sites.google.com/site/hydrothecs/library-1/crossthread