日期:2014-05-20 浏览次数:20963 次
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Thread t = null;
ABC a = new ABC();
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
if (t == null) {
t = new Thread(Proc);
t.IsBackground = true;
t.Start();
}
}
private void Proc() {
while (true) {
string str = a.GetStr();
if (label1.InvokeRequired) {
label1.Invoke(new MethodInvoker(delegate { label1.Text = str; }));
} else
label1.Text = str;
Thread.Sleep(1000);
}
}
}
class ABC
{
public string GetStr() {
return DateTime.Now.ToString();
}
}
}
------解决方案--------------------
Form1运行的是主线程,.netframework从2.0以后加入了线程安全特性,所以辅助线程不能直接访问主线程内的资源(label)
但Control提供了Invoke,BeginInvoke方法,可以跨线程安全访问。