线程类-传递参数并更新控件

来源:互联网 发布:刷年费会员软件 编辑:程序博客网 时间:2024/06/05 20:02

   定义一个class1线程类,添加线程并启动,线程工作时调用事件,通过界面线程订阅事件来实现线程类与界面线程通信的方法。

namespace threadclass

   public delegate void ReadParamEventHandler(string sParam);
    public class Class1
    {
        public Thread thread1;
        private static ReadParamEventHandler OnReadParamEvent;
        public Class1()
        {
            thread1 = new Thread(new ThreadStart(MyRead));
            thread1.IsBackground = true;
            thread1.Start();
        }
        public event ReadParamEventHandler ReadParam
        {
            add { OnReadParamEvent += new ReadParamEventHandler(value); }
            remove { OnReadParamEvent -= new ReadParamEventHandler(value); }
        }
        protected void MyRead()
        {
            int i = 0;
            while (true)
            {
                Thread.Sleep(1000);
                i = i + 1;
                OnReadParamEvent(i.ToString());//触发事件  
            }
        }

添加窗体Form1和lable,然后添加如下代码:

 public Form4()
        {
            InitializeComponent();
            Class1 cl1 = new Class1();
            cl1.ReadParam += this.OnRead;
               
        }

  private void OnRead(string sParam)
        {
            param = sParam;
            Object[] list = { this, System.EventArgs.Empty };
            this.lblShow.BeginInvoke(new EventHandler(LabelShow), list);
        }
        protected void LabelShow(Object o, EventArgs e)
        {
            this.lblShow.Text = param;
        } 

this.lblShow.BeginInvoke(new EventHandler(LabelShow), list);

使用 Invoke完成一个委托方法的封送,是一个同步方法。也就是说在 Invoke封送的方法被执行完毕前, Invoke方法不会返回,从而调用者线程将被阻塞。

使用 BeginInvoke方法封送一个委托方法,这是一个异步方法。也就是该方法封送完毕后马上返回,不会等待委托方法的执行结束,调用者线程将不会被阻塞。但是调用者也可以使用 EndInvoke方法或者其它类似 WaitHandle机制等待异步操作的完成。

 

add 上下文关键字用于定义一个自定义事件访问器,当客户端代码订阅您的事件时将调用该访问器。如果提供自定义 add 访问器,还必须提供 remove访问器。

remove 上下文关键字用于定义一个自定义事件访问器,当客户端代码取消订阅事件时将调用该访问器。如果提供自定义 remove 访问器,还必须提供add访问器。

 

 

原创粉丝点击