日期:2014-05-18 浏览次数:21090 次
//主窗体 public partial class DelegateBeginInvoke : Form { public DelegateBeginInvoke() { InitializeComponent(); } //定义与方法同签名的委托 private delegate string DelegateName(int num, out int ret); private delegate void DelegateA(); private delegate void Delegate赋值(string 值); formTimer f = new formTimer(); //要进行异步的方法 private string MethodName(int num, out int ret) { ret = num; System.Threading.Thread.Sleep(10000); return "HelloWorld"; } private void button1_Click(object sender, EventArgs e) { label1.Text = ""; //实例化委托并初赋值 DelegateName dn = new DelegateName(MethodName); int i; //实例化回调函数,把AsyncCallback看成是Delegate就懂了,实际上AsyncCallback是一种特殊的Delegate AsyncCallback acb = new AsyncCallback(CallBackMethod); //异步开始 //如果参数acb换成null则表示没有回调方法 //最后一个参数dn的地方,可以换成任意对象,该对象可以被回调方法从参数中获取出来,写成null也可以。 //参数dn相当于该线程的ID,如果有多个异步线程,可以都是null,但是绝对不能一样,不能是同一个object,否则异常 IAsyncResult iar = dn.BeginInvoke(1, out i, acb, dn); textBox1.Text = Environment.UserName.ToString(); f = new formTimer(); f.Show(); } //回调方法(异步完成时,执行的方法,此方法只有IAsyncResult一个参数,但是该参数几乎万能,可以传递Object) private void CallBackMethod(IAsyncResult ar) { DelegateName dn = (DelegateName)ar.AsyncState; int i; string r = dn.EndInvoke(out i, ar);//一定要EndInvoke,否则你的下场很惨 DelegateA dd = new DelegateA(formClose); if (f.InvokeRequired) this.Invoke(dd); else formClose(); //MessageBox.Show("异步完成了!i的值是" + i.ToString() + ",r的值是" + r); Delegate赋值 dd赋值 = new Delegate赋值(赋值); if (label1.InvokeRequired) { this.Invoke(dd赋值, new object[] { "异步完成了!i的值是" + i.ToString() + ",r的值是" + r }); } else { textBox1.Text = "异步完成了!i的值是" + i.ToString() + ",r的值是" + r; } } void formClose() { f.Close(); } void 赋值(string aa) { label1.Text = aa; } }
------解决方案--------------------
//弹出的提示窗体 public partial class formTimer : Form { public formTimer() { InitializeComponent(); } DateTime a = DateTime.Now; private void formTimer_Load(object sender, EventArgs e) { label1.Text = (DateTime.Now - a).Seconds.ToString(); timer1.Enabled = true; } private void timer1_Tick(object sender, EventArgs e) { label1.Text = (DateTime.Now - a).Seconds.ToString(); } } //弹出窗体的designer.cs文件 用于构建界面友好 partial class formTimer { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { co