不知道为什么 我用C#的线程操作 控件的时候就报错 , 请高手帮忙解答!using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsApplication82
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
Thread tH = new Thread(new ThreadStart(ThreadStart));
tH.Start();
} private void ThreadStrat()
{
for (int i = 0; i < 100; i++)
{
checkedListBox1.Items.Add("这是" + i.ToString());
Thread.Sleep(2000);
}
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsApplication82
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
Thread tH = new Thread(new ThreadStart(ThreadStart));
tH.Start();
} private void ThreadStrat()
{
for (int i = 0; i < 100; i++)
{
checkedListBox1.Items.Add("这是" + i.ToString());
Thread.Sleep(2000);
}
}
}
}
使用Invoke。
{
if(checkedListBox1.InvokeRequired){
ThreadStart ts = new ThreadStart(ThreadStrat);
checkedListBox1.Invoke(ts);
}else{
for (int i = 0; i < 100; i++)
{
checkedListBox1.Items.Add("这是" + i.ToString());
Thread.Sleep(2000);
}
}
}
如果要解决这个问题,主要应用Control.Invoke方法,它能接收一个委托
MethodInvoker invoker = new MethodInvoker(this.InvokeUIThead);
this.Invoke(invoker);
在this.InvokeUIThead里面实现对窗体元素的更新.
private void ThreadStrat()
{
MethodInvoker invoker = new MethodInvoker(this.InvokeUIThead);
for (int i = 0; i < 5; i++)
{
item = i;
this.Invoke(invoker);
Thread.Sleep(2000);
}
} private void InvokeUIThead()
{
checkedListBox1.Items.Add("这是" + item.ToString());
}
但是最简单的方法是:
在窗体的load事件中这样写:
system.windows.forms.form.checkfor*** = false;不好意思,单词忘了。