线程安全的问题
我想完成
点一个按钮以后用两个线程
给Form1上的listbox1添加一些内容
我是用如下的代码做的
private void button1_Click(object sender, EventArgs e)
{
Thread OneThread = new Thread(new ThreadStart(this.Run1));
OneThread.Name = "one ";
Thread TowThread = new Thread(new ThreadStart(this.Run2));
TowThread.Name = "tow ";
OneThread.Start();
TowThread.Start();
}
private void Run1()
{
for (int i = 0; i < 100; i++)
{
this.listBox1.Items.Add(Thread.CurrentThread.Name + i.ToString());
}
}
private void Run2()
{
for (int i = 0; i > -100; i--)
{
this.listBox1.Items.Add(Thread.CurrentThread + i.ToString());
}
}
但this.listBox1.Items.Add(Thread.CurrentThread.Name + i.ToString());提示
从不是创建控件listBox1的线程访问它
不知道应该怎么做
------解决方案--------------------声明一个delegate控制显示,线程中用Invoke执行delegate
------解决方案--------------------try..
//定义一个互斥量,用于对ListBox的互斥访问
Mutex mx=new Mutex();
public delegate void MyInvoke(string str);
private void UpdateListBox(string str)
{
//更新
mx.WaitOne();
this.listBox1.Items.Add(str);
mx.ReleaseMutex();
}
private void button1_Click(object sender, EventArgs e)
{
Thread OneThread = new Thread(new ThreadStart(this.Run1));
OneThread.Name = "one ";
Thread TowThread = new Thread(new ThreadStart(this.Run2));
TowThread.Name = "tow ";
OneThread.Start();