//一定要EndInvoke,否则你的下场很惨 string r = dn.EndInvoke(out i, ar); MessageBox.Show("异步完成喽!i的值是" i.ToString() ",r的值是" r); }
//定义与方法同签名的委托 private delegate string DelegateName(int Num, out int Num2);
//程序入口 private void Run() { //实例化委托并初赋值 DelegateName dn = new DelegateName(MethodName); //输出参数 int i; //实例化回调方法 //把AsyncCallback看成Delegate你就懂了,实际上AsyncCallback是一种特殊的Delegate,就像Event似的 AsyncCallback acb = new AsyncCallback(CallBackMethod); //异步开始 //如果参数acb换成null则表示没有回调方法 //最后一个参数dn的地方,可以换成任意对象,该对象可以被回调方法从参数中获取出来,写成null也可以。参数dn相当于该线程的ID,如果有多个异步线程,可以都是null,但是绝对不能一样,不能是同一个object,否则异常 IAsyncResult iar = dn.BeginInvoke(1, out i, acb, dn); //去做别的事 //………… }
//最后的结果应该是:i=1,r="HelloWorld"
另外,如果可以,定义委托的时候可以选择不用过多的修饰:
/// /// 定义委托 /// /// public delegate bool Asyncdelegate();
/// /// Callback method must have the same signature as the /// AsyncCallback delegate /// /// private void CallbackMethod(IAsyncResult ar) { // Retrieve the delegate. Asyncdelegate dlgt = (Asyncdelegate)ar.AsyncState;
// Call EndInvoke to retrieve the results. dlgt.EndInvoke(ar); }
其他方法中调用: //异步执行 //指定委托方法 Asyncdelegate isgt = new Asyncdelegate(icpInfo.Insert); IAsyncResult ar = isgt.BeginInvoke(new AsyncCallback(CallbackMethod), isgt);