//閑來無事,鞏固同步異步方面的知識,以備后用,特整理如下:
class PRogram { static void Main(string[] args) { //同步調用 會阻塞當前線程,一步一步進行調用 Console.WriteLine("============同步調用線程:" + Thread.CurrentThread.ManagedThreadId+"============"); AddHandler _handler01 = AddMethod.Add; int _result01 = _handler01(1, 2); Console.WriteLine("繼續做別的事情。。。"); Console.WriteLine("同步調用結果:"+_result01); Console.WriteLine(); //異步調用 不會阻塞當前線程,會放到線程池里 //異步調用通過BeginInvoke和EndInvoke來實現(成對應用)。 Console.WriteLine("============異步調用線程:" + Thread.CurrentThread.ManagedThreadId + "============"); AddHandler _handler02 = AddMethod.Add; IAsyncResult _result02 = _handler02.BeginInvoke(3, 8, null, null); Console.WriteLine("繼續做別的事情。。。"); Console.WriteLine("異步調用結果:"+_handler02.EndInvoke(_result02)); Console.WriteLine(); //用回調函數,當調用結束時會自動調用回調函數,解決了為等待調用結果,而讓線程依舊被阻塞的局面。 //BeginInvoke最后一個參數@object傳遞額外的參數 Console.WriteLine("============異步回調 線程:" + Thread.CurrentThread.ManagedThreadId + "============"); AddHandler _handler03 = AddMethod.Add; IAsyncResult _result03 = null; _result03 = _handler03.BeginInvoke(9, 8, (IAsyncResult _ia) => { Console.WriteLine("異步回調結果:"+_handler03.EndInvoke(_result03)); }, null); Console.WriteLine("繼續做別的事情。。。"); Console.ReadKey(); } } public delegate int AddHandler(int _a,int _b); public class AddMethod { public static int Add(int _a, int _b) { Console.WriteLine("開始計算:" + _a + "+" + _b); Thread.Sleep(3000); Console.WriteLine("計算完成! 線程:"+Thread.CurrentThread.ManagedThreadId); return _a + _b; } } }
//運行結果,如圖:
整理自:http://blog.csdn.net/wanlong360599336/article/details/8781477
新聞熱點
疑難解答