c#異步Begininvoke使用隨筆


 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM