listBox1.InvokeRequired学习

控件只能由创建它的线程来访问。其他线程想访问必须调用该控件的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]);
}
}
}
}
}

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

多线程可以解决用户响应

namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private delegate void addlistdlg(string str);
private Thread mythread;

private void addlistmethod(string mystr)
{
listBox1.Items.Add(mystr);
}
private void addlistfun()
{

for (int i = 1; i < 90000; i++)
{
string mystr = “第” + i.ToString() + “个”;

if (listBox1.InvokeRequired)
listBox1.Invoke(new addlistdlg(addlistmethod), new Object[] { mystr });
else
listBox1.Items.Add(mystr);
}
}

private void button2_Click(object sender, EventArgs e)//执行就会卡死
{
mythread = new Thread(new ThreadStart(addlistfun));
mythread.Start();
}
}
}

if (listBox1.InvokeRequired)
listBox1.Invoke(new addlistdlg(addlistmethod), new Object[] { mystr });
else
listBox1.Items.Add(mystr);

的else部分只是我帮你补完整而已,就是变成如果不是线程里运行也可以执行的通用代码
实例在里这是每次执行
listBox1.Invoke(new addlistdlg(addlistmethod), new Object[] { mystr });

namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private delegate void addlistdlg(string str);
private Thread mythread;

private void addlistmethod(string mystr)
{
listBox1.Items.Add(mystr);
}
private void addlistfun()
{

for (int i = 1; i < 90000; i++)
{
string mystr = “第” + i.ToString() + “个”;

if (listBox1.InvokeRequired)
listBox1.Invoke(new addlistdlg(addlistmethod), new Object[] { mystr });
else
listBox1.Items.Add(mystr);
Thread.Sleep(1000);
}
}

private void button2_Click(object sender, EventArgs e)//执行就会卡死
{
mythread = new Thread(new ThreadStart(addlistfun));
mythread.Start();
}
}
}
在循环中加Thread.Sleep(1000);

转自http://lyq888.blog.sohu.com/104963902.html

0 Comments
Leave a Reply

Time limit is exhausted. Please reload the CAPTCHA.