C#(Winform) 跨執行緒訪問解決辦法
阿新 • • 發佈:2019-01-28
網上的資料很多,這裡直接摘抄。
1、關閉跨執行緒檢查。
CheckForIllegalCrossThreadCalls = false;
2、通過委託的方式,在控制元件的執行緒上執行。
using System;using System.Threading;using System.Windows.Forms;namespace WindowsFormsApplication1
{ public partial class Form2 : Form
{ public Form2()
{
InitializeComponent(); //方法一:不進行跨執行緒安全檢查
CheckForIllegalCrossThreadCalls = false;
} private void button1_Click(object sender, EventArgs e)
{
Thread th1 = new Thread(new ThreadStart(CalNum));
th1.Start();
} private void CalNum()
{
SetCalResult(DateTime.Now.Second);
} //方法二:檢查是否跨執行緒,然後將方法加入委託,呼叫委託
public delegate void SetTextHandler(int result);
private void SetCalResult(int result)
{ if (label2.InvokeRequired == true)
{
SetTextHandler set = new SetTextHandler(SetCalResult);//委託的方法引數應和SetCalResult一致
label2.Invoke(set , new object[] { result }); //此方法第二引數用於傳入方法,代替形參result
}
else
{
label2.Text = result.ToString();
}
}
}
}