在拥有此控件的基础窗口句柄的线程上执行指定的委托。
public Object Invoke (
Delegate method
)
参数
-
method
-
包含要在控件的线程上下文中调用的方法的委托。
返回值
正在被调用的委托的返回值,或者如果委托没有返回值,则为 空引用(在 Visual Basic 中为 Nothing)。
// The following code assumes a 'ListBox' and a 'Button' control are added to a form, // containing a delegate which encapsulates a method that adds items to the listbox. public class MyThreadClass { MyFormControl myFormControl1; public MyThreadClass(MyFormControl myForm) { myFormControl1 = myForm; } public void Run() { // Execute the specified delegate on the thread that owns // 'myFormControl1' control's underlying window handle. myFormControl1.Invoke(myFormControl1.myDelegate); } }
Control.Invoke 方法 (Delegate, Object[])在拥有控件的基础窗口句柄的线程上,用指定的参数列表执行指定委托。
public Object Invoke ( Delegate method, params Object[] args )
参数
method
一个方法委托,它采用的参数的数量和类型与 args 参数中所包含的相同。
args
作为指定方法的参数传递的对象数组。如果此方法没有参数,该参数可以是 空引用(在 Visual Basic 中为 Nothing)。
返回值
Object,它包含正被调用的委托返回值;如果该委托没有返回值,则为 空引用(在 Visual Basic 中为 Nothing)。using System; using System.Drawing; using System.Windows.Forms; using System.Threading; public class MyFormControl : Form { public delegate void AddListItem(String myString); public AddListItem myDelegate; private Button myButton; private Thread myThread; private ListBox myListBox; public MyFormControl() { 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); } static void Main() { MyFormControl myForm = new MyFormControl(); myForm.ShowDialog(); } public void AddListItemMethod(String myString) { myListBox.Items.Add(myString); } private void Button_Click(object sender, EventArgs e) { myThread = new Thread(new ThreadStart(ThreadFunction)); myThread.Start(); } private void ThreadFunction() { MyThreadClass myThreadClassObject = new MyThreadClass(this); myThreadClassObject.Run(); } } public class MyThreadClass { MyFormControl myFormControl1; public MyThreadClass(MyFormControl myForm) { myFormControl1 = myForm; } String myString; public void Run() { for (int i = 1; i <= 5; i++) { myString = "Step number " + i.ToString() + " executed"; Thread.Sleep(400); // Execute the specified delegate on the thread that owns // 'myFormControl1' control's underlying window handle with // the specified list of arguments. myFormControl1.Invoke(myFormControl1.myDelegate, new Object[] {myString}); } } }