Control.Invoke 方法 (Delegate)
在拥有此控件的基础窗口句柄的线程上执行指定的委托。
Invoke方法搜索沿控件的父级链,直到它找到的控件或窗口具有一个窗口句柄;
如果尚不存在当前控件的基础窗口句柄,或者找不到任何合适的句柄,Invoke方法
将会引发异常。
例子
public class MyFormControl : Form { public delegate void AddListItem(); public AddListItem myDelegate; private Thread myThread; private ListBox myListBox; public MyFormControl() { var myButton = new Button(); myListBox = new ListBox(); myButton.Location = new Point(72, 160); myButton.Size = new Size(152, 32); myButton.TabIndex = 1; myButton.Text = "Add items in list box"; myButton.Click += new EventHandler(Button_Click); myListBox.Location = new Point(48, 32); myListBox.Name = "myListBox"; myListBox.Size = new Size(200, 95); myListBox.TabIndex = 2; ClientSize = new Size(292, 273); Controls.AddRange(new Control[] { myListBox, myButton }); Text = " 'Control_Invoke' example"; myDelegate = new AddListItem(AddListItemMethod); } public void AddListItemMethod() { String myItem; for (int i = 1; i < 6; i++) { myItem = "MyListItem" + i.ToString(); myListBox.Items.Add(myItem); myListBox.Update(); Thread.Sleep(3000); } } private void Button_Click(object sender, EventArgs e) { myThread = new Thread(new ThreadStart(ThreadFunctionRight)); myThread.Start(); } }
关键
private void ThreadFunctionWrong() { //if direct call myDelegate(), it would throw an exception myDelegate(); } private void ThreadFunctionRight() { //right way: must run at thead that creates myListBox control. // Execute the specified delegate on the thread that owns // 'myListBox' control's underlying window handle. this.Invoke(this.myDelegate); }