Control.Invoke 方法 (Delegate, Object[]) ,执行委托

在拥有控件的基础窗口句柄的线程上,用指定的参数列表执行指定委托。

参数

method
类型:System ..::.Delegate

一个方法委托,它采用的参数的数量和类型与 args 参数中所包含的相同。

args
类型: array<System ..::.Object >[]()[]

作为指定方法的参数传递的对象数组。如果此方法没有参数,该参数可以是 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing

返回值

类型:System ..::.Object

Object,它包含正被调用的委托返回值;如果该委托没有返回值,则为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing


例如:Form1中有两个控件,button1,listbox1,点击按钮,在listbox上面添加项目

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace @delegate
{
    public partial class Form1 : Form
    {
        public delegate void AddListItem(String myString);  //定义委托类型
        public AddListItem myDelegate;                      //定义委托变量
        private Thread myThread;                            //定义线程


        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            myDelegate = new AddListItem(AddListItemMethod);          //初始化委托变量
            myThread = new Thread(new ThreadStart(ThreadFunction));   //定义线程
            myThread.Start();
        }


        public void AddListItemMethod(String myString)
        {
            listBox1.Items.Add(myString);
        }
        private void ThreadFunction()
        {
            MyThreadClass myThreadClassObject = new MyThreadClass(this);
            myThreadClassObject.Run();       //调用run方法
        }


    }


    public class MyThreadClass
    {
        Form1 myFormControl1;
        public MyThreadClass(Form1 myForm)
        {
            myFormControl1 = myForm;
        }
        String myString;


        public void Run()
        {
            for (int i = 1; i <= 5; i++)
            {
                myString = "Step number " + i.ToString() + " executed";
                Thread.Sleep(400);
                myFormControl1.Invoke(myFormControl1.myDelegate,
                                       new Object[] { myString });   //执行委托
            }
        }
    }


}

你可能感兴趣的:(thread,object,String,basic,Class,button)