线程间操作无效: 从不是创建控件的线程访问它.
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.Threading; 10 11 namespace LoginIn 12 { 13 public partial class Form1 : Form 14 { 15 delegate void MyDelegate(string name, string code); 16 delegate void SetTipDelegate(string tip); 17 public Form1() 18 { 19 InitializeComponent(); 20 } 21 22 private void button1_Click(object sender, EventArgs e) 23 { 24 string name = txtName.Text; 25 string code = txtCode.Text; 26 //调用委托,用新线程校验用户名、密码 27 MyDelegate myDelegate = new MyDelegate(CheckUser); 28 myDelegate.BeginInvoke(name, code, null, null); 29 } 30 31 void CheckUser(string name, string code) 32 { 33 Thread.Sleep(2000); 34 if (name == "1" && code == "1") 35 { 36 SetTip("成功"); 37 } 38 else 39 { 40 SetTip("失败"); 41 } 42 } 43 44 void SetTip(string tip) 45 { 46 //是否调用Invoke方法 47 if (lbTip.InvokeRequired) 48 //if(!从创建控件“lbTip”的线程访问它) 49 { 50 //调用委托 51 SetTipDelegate myDelegate = new SetTipDelegate(SetTip); 52 Invoke(myDelegate, tip); 53 } 54 else 55 { 56 lbTip.Text = tip; 57 } 58 } 59 60 private void timer1_Tick(object sender, EventArgs e) 61 { 62 button1.Text = DateTime.Now.ToString(); 63 } 64 } 65 }
2015年8月3日 16:49:27,更新简写版
1 protected void button1_Click(object sender,EventArgs e) 2 { 3 string userName = txtName.Text; 4 string userCode = txtCode.Text; 5 6 Func<string ,string ,string> d1 = (name, code) => 7 (name == "1" && code == "1") ? "成功" : "失败"; 8 9 d1.BeginInvoke(userName,userCode,ar=> 10 { 11 string result= d1.EndInvoke(ar); 12 Action<string> action1=data=>label1.Text=data; 13 Invoke(action1,result); 14 }, 15 null); 16 }