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 });   //执行委托
            }
        }
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值