异步委托

  示例程序中,用异步线程判断用户名、密码是否正确,并显示在界面上。 

 1         protected void button1_Click(object sender,EventArgs e)
 2         {
 3             //用户名、密码
 4             string userName = txtName.Text;
 5             string userCode = txtCode.Text;
 6             
 7             //定义委托,返回判断结果字符串
 8             Func<string ,string ,string> d1 = (name, code) =>           
 9                  (name == "1" && code == "1") ? "成功" : "失败";                            
10                 
11             //异步调用            
12             d1.BeginInvoke(userName,userCode,ar=>
13                            {
14                                //回调函数
15                                //拿判断结果
16                                string result= d1.EndInvoke(ar);
17                                //再次用委托(避免跨线程访问控件错误)显示结果。实际应用中可能是关闭遮罩,显示结果等
18                                Action<string> action1=data=>label1.Text=data;
19                                Invoke(action1,result);
20                            },
21                            null);
22         }
原文地址:https://www.cnblogs.com/David-Huang/p/4699871.html