您的位置:首页 > 编程语言 > C#

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

2008-07-16 14:51 477 查看
最近做软件自动升级的程序,发现用新建的工作进程访问进度条控件有错误。细察原因发现,控件只能由创建它的线程来访问。其他线程想访问必须调用该控件的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]);
}
}
}
}
}

这样就实现了新建的工作进程对控件的访问。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: