一、System.Windows.Forms.MethodInvoker 类型是一个系统定义的委托,用于调用不带参数的方法。
private Thread myThread;
private void Form1_Load(object sender, EventArgs e)
{
myThread = new Thread(new ThreadStart(RunsOnWorkerThread));
myThread.Start();
}
private void RunsOnWorkerThread()
{
MethodInvoker mi = new MethodInvoker(SetControlsProp);
BeginInvoke(mi);
}
private void SetControlsProp()
{
label1.Text = "myThread线程调用UI控件";
}
二、直接用System.EventHandle(可带参数)
private Thread myThread;
private void Form1_Load(object sender, EventArgs e)
{
myThread = new Thread(new ThreadStart(RunsOnWorkerThread));
myThread.Start();
}
private void RunsOnWorkerThread()
{
//DoSomethingSlow();
string pList = "myThread线程调用UI控件";
label1.BeginInvoke(new System.EventHandler(UpdateUI), pList);
}
//直接用System.EventHandler,没有必要自定义委托
private void UpdateUI(object o, System.EventArgs e)
{
//UI线程设置label1属性
label1.Text = o.ToString() + "成功!";
}
三、演示程序
/// <summary>
/// 提供给系统委托事件调用,解决线程内操作界面控件的目的
/// </summary>
/// <param name="obj"></param>
/// <param name="e"></param>
private void UpdateListBox(object obj,System.EventArgs e)
{
//强制类型转换
List<String> paramList = (List<string>)obj;
if (paramList[0] == "0")
{
this.lstBoxCatchData.Items.Clear();
}
else if (paramList[0] == "1")
{
this.lstBoxCatchData.Items.Add(paramList[1].ToString());
}
}
线程中调用部分:
//初始化参数列表
List<String> paramList = new List<string>();
paramList.Add("0");
paramList.Add("");
//这里采用系统委托的方式,实现线程内操作系统界面控件。
paramList[0] = "0"; paramList[1] = "清除屏幕信息";
lstBoxCatchData.BeginInvoke(new System.EventHandler(UpdateListBox), paramList);
结束。