現在電腦大部分都是多核心,在處理多線程方便有很大優勢,異步調用方法的時候可以立即返回執行其他程序,進行異步編程會讓程序運行效率更高。
我也是剛剛關注異步編程方面知識,也有很多不是很理解,所以想向大神請教關於.net異步編程的一些問題。
1、異步編程原理,主程序和異步程序還有回調函數分別什么線程上,執行順序?
2、怎么使回調函數獲取異步返回值,並在回調完畢后關閉主程序?
3、能否主程序結束,異步程序還可以繼續執行,執行完畢后執行回調?
4、異步編程實際應用的作用如何,真正能帶來多大好處?想用異步編程,如何更好的運用?
下面是我寫的代碼:
1 /*Author:liulei 2 *Des:異步編程測試 3 *Date:2013-10-29 4 */ 5 using System; 6 using System.Collections.Generic; 7 using System.Data; 8 using System.Data.Common; 9 using System.Linq; 10 using System.Text; 11 using System.Threading; 12 using Microsoft.Practices.EnterpriseLibrary.Data; 13 14 namespace AsyncApplication 15 { 16 class Program 17 { 18 19 static void Main(string[] args) 20 { 21 Console.WriteLine("主程序開始!"); 22 Func<int> caller = new Func<int>(CreateUser); 23 Console.WriteLine("異步開始!"); 24 IAsyncResult ar = caller.BeginInvoke(new AsyncCallback(CallBackMethod), caller); 25 caller.EndInvoke(ar); 26 Console.WriteLine("主程序完成!"); 27 } 28 29 //回調方法 30 static void CallBackMethod(IAsyncResult ar) 31 { 32 Func<int> a = (Func<int>)ar.AsyncState; 33 int result = a.EndInvoke(ar);//這樣是可以獲取異步的返回值,可是進行到這里,回調程序就結束了,不會執行下面程序! 34 Console.WriteLine("回調完成!"); 35 } 36 //創建用戶 37 static int CreateUser() 38 { 39 Database db = CreateDatabase(); 40 string sql = "insert into [User] (Name,Password) values (@Name,@Password);select @@identity"; 41 DbCommand dc = db.GetSqlStringCommand(sql); 42 db.AddInParameter(dc, "@Name", DbType.String, "zhaoliang"); 43 db.AddInParameter(dc, "@Password", DbType.String, "456"); 44 var ob = db.ExecuteScalar(dc); 45 return Convert.ToInt16(ob); 46 47 } 48 //創建Database 49 static Database CreateDatabase() 50 { 51 Database db = DatabaseFactory.CreateDatabase("ConnectionString"); 52 return db; 53 } 54 } 55 }
大家有什么關於異步編程好的理解,可以提出來大家一起討論學習,謝謝。