标签:
public partial class Form1 : Form { public Form1() { InitializeComponent(); //方法一:不进行跨线程安全检查 //System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; } private void button1_Click(object sender, EventArgs e) { Thread th1 = new Thread(new ThreadStart(CalNum)); th1.Start(); } private void CalNum() { //button1.Enabled = false; int result = 0; for (int i = 1; i < 100000000; i++) { result += i; } SetCalResult(result); //button1.Enabled = true; } //方法二:检查是否跨线程,然后将方法加入委托,调用委托 public delegate void SetTextHandler(int result); private void SetCalResult(int result) { if (label2.InvokeRequired) //等待异步 { SetTextHandler set = new SetTextHandler(SetCalResult);//委托的方法参数应和SetCalResult一致 label2.Invoke(set, new object[] { result }); //此方法第二参数用于传入方法,代替形参result } else { label2.Text = result.ToString(); } } }
标签:
原文地址:http://www.cnblogs.com/luciakally/p/4851746.html