在线程委托中实现参数的传递

来源:互联网 发布:淘宝品牌授权书真假 编辑:程序博客网 时间:2024/04/28 10:24

 在用线程委托对Windows窗体控件进行操作时,有时需要在线程委托中以参数的形式判断当前线程的执行方式,下面以简单的例子在子线程中以两种方式操作窗体中的TextBox控件。代码如下:

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 ppp

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        Thread t; //定义线程变量

 

        private void button1_Click(object sender, EventArgs e)

        {

            t = new Thread(new ThreadStart(Threadp)); //实例化线程

            t.Start();//启动线程

        }

        定义一个带参数的线程委托。

        private delegate void setText(bool b);

        自定义方法Threadp,主要用于线程的调用。代码如下:

        public void Threadp()

        {

            setText d = new setText(Threading);

            this.BeginInvoke(d, new object[] { checkBox1.Checked });

        }

        自定义带有参数的方法Threading,主要作于委托的调用。代码如下:

        public void Threading(bool b)

        {

            if (b)

            {

                textBox1.Text = "复选框被选中,执行相应的操作";

            }

            else

            {

                textBox1.Text = "复选框没有被选中,执行相应的操作";

            }

            t.Abort();

        }

    }

}

         在线程的委托中,也可以定义多个参数,下面对上的部份代码进行一下修改,以说明如何在委托中定义多个参数。代码如下:

        public void Threadp()

        {

            setText d = new setText(Threading);

            this.BeginInvoke(d, new object[] { checkBox1.Checked, 0 });

        }


        private delegate void setText(bool b,int n);

        public void Threading(bool b,int n)

        {

            if (b)

            {

                textBox1.Text = "复选框被选中,执行相应的操作";

            }

            else

            {

                textBox1.Text = "复选框没有被选中,执行相应的操作";

            }

            t.Abort();

        }

原创粉丝点击