1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace WindowsFormsApplication1 8 { 9 public class delegateclass 10 { 11 private delegate int Dothread(); 12 static Dothread dothread = new Dothread(work); 13 14 public static void start() 15 { 16 AsyncCallback backCall = new AsyncCallback(backcall);
18 dothread.BeginInvoke(backCall, "我是异步调用的parameter");//第一个参数是调用work方法的参数,第二个是回调函数,第三个是需要传到回调函数里的参数可以是Object类型 19 } 20 /// <summary> 21 ///这个是委托调用程序 22 /// </summary> 23 private static int work() 24 { 25 System.Windows.Forms.MessageBox.Show("我是委托调用程序"); 26 return 999; 27 28 } 29 /// <summary> 30 /// 回调函数 31 /// </summary> 32 /// <param name="parameter"></param> 33 /// <returns></returns> 34 private static int backcall(int parameter) 35 { 36 System.Windows.Forms.MessageBox.Show("这是一个回调函数"); 37 return 0; 38 39 } 40 private static void backcall(IAsyncResult parameter) 41 { 42 int result=dothread.EndInvoke(parameter); 43 System.Windows.Forms.MessageBox.Show("这是一个回调函数"); 44 System.Windows.Forms.MessageBox.Show(result.ToString()); 45 System.Windows.Forms.MessageBox.Show(parameter.AsyncState.ToString()); 46 47 48 } 49 } 50 51 }
上面是建立的一个类,因时间不多,命名比较随意。
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.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace WindowsFormsApplication1 12 { 13 public partial class Form1 : Form 14 { 15 public Form1() 16 { 17 InitializeComponent(); 18 } 19 20 private void button1_Click(object sender, EventArgs e) 21 { 22 delegateclass.start(); 23 } 24 } 25 }
原文:http://www.cnblogs.com/shucaige/p/6392028.html