C#程序利用线程访问控件

来源:互联网 发布:淘宝看店宝怎么安装 编辑:程序博客网 时间:2024/04/28 15:25

   最近做软件自动升级的程序,发现用新建的工作进程访问进度条控件有错误。细察原因发现,控件只能由创建它的线程来访问。其他线程想访问必须调用该控件的Invoke方法。Invoke有两个参数,一个是委托方法,一个是参数值。下面代码就是举例为ListBox添加数据。

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

namespace TestAutoUpEBooks
{
    public partial class Form1 : Form
    {
        delegate void SetListBox(string[] strValues);                   定义委托

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread tr = new Thread(new ThreadStart(SetListBoxV));   创建线程
            tr.Start();                                                                              启动线程
        }

        private void SetListBoxV()
        {
            string[] s = new string[3] {"a","b","c"};
            SetListBoxValue(s);
        }

        private void SetListBoxValue(string[] values)
        {
            if (this.listBox1.InvokeRequired)                           当有新工作进程访问控件时InvokeRequired为True
            {
                SetListBox slb = new SetListBox(SetListBoxValue);  定义委托对象
                listBox1.Invoke(slb, new object[] { values});     用当前工作进程对控件进行访问

        }
            else      对ListBox添加数据
            {
                for (int i = 0; i < values.Length; i++)
                {
                    listBox1.Items.Add((object)values[i]);
                }
            }
        }
    }
}

这样就实现了新建的工作进程对控件的访问。

原创粉丝点击