在CSDN上看到的一篇如果线程安全的来操作控件的帖子。才发现自己只接触了C#的皮毛,把代码贴一下:
using System;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication15
{
public static class Extensions
{
public static void SafeCall(this Control ctrl, Action callback)
{
if (ctrl.InvokeRequired)
ctrl.Invoke(callback);
else
callback();
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 下面这些就是关键了。。。真的很震撼的。。。
ThreadPool.QueueUserWorkItem(h =>
{
int i = 0;
while (true)
{
label1.SafeCall(() =>
{
label1.Text = i.ToString();
++i;
}
);
Thread.Sleep(1000);
}
}
);
}
}
}
原帖地址:http://www.csdn.net/article/2012-08-18/2808603