C# 委託的同步呼叫和非同步呼叫--抓住重點
阿新 • • 發佈:2018-10-31
委託的Invoke方法用來進行同步呼叫。同步呼叫也可以叫阻塞呼叫,它將阻塞當前執行緒,然後執行呼叫,呼叫完畢後再繼續向下進行。
同步呼叫的例子:
using System; using System.Threading; public delegate int AddHandler(int a, int b); public class Foo { static void Main() { Console.WriteLine("**********SyncInvokeTest**************"); AddHandler handler = new AddHandler(Add); int result = handler.Invoke(1,2); Console.WriteLine("Do other work... ... ..."); Console.WriteLine(result); Console.ReadLine(); } static int Add(int a, int b) { Console.WriteLine("Computing "+a+" + "+b+" ..."); Thread.Sleep(3000); Console.WriteLine("Computing Complete."); return a+b; } }
執行結果:
**********SyncInvokeTest**************
Computing 1 + 2 ...
Computing Complete.
Do other work... ... ...
3
同步呼叫會阻塞執行緒,如果是要呼叫一項繁重的工作(如大量IO操作),可能會讓程式停頓很長時間,造成糟糕
的使用者體驗,這時候非同步呼叫就很有必要了。
非同步呼叫不阻塞執行緒,而是把呼叫塞到執行緒池中,程式主執行緒或UI執行緒可以繼續執行。
委託的非同步呼叫通過BeginInvoke和EndInvoke來實現。
非同步呼叫:
using System; using System.Threading; public delegate int AddHandler(int a, int b); public class Foo { static void Main() { Console.WriteLine("**********AsyncInvokeTest**************"); AddHandler handler = new AddHandler(Add); IAsyncResult result = handler.BeginInvoke(1,2,null,null); Console.WriteLine("Do other work... ... ..."); Console.WriteLine(handler.EndInvoke(result)); Console.ReadLine(); } static int Add(int a, int b) { Console.WriteLine("Computing "+a+" + "+b+" ..."); Thread.Sleep(3000); Console.WriteLine("Computing Complete."); return a+b; } }
執行結果: **********AsyncInvokeTest**************
Do other work... ... ...
Computing 1 + 2 ...
Computing Complete.
3
可以看到,主執行緒並沒有等待,而是直接向下運行了。
但是問題依然存在,當主執行緒執行到EndInvoke時,如果這時呼叫沒有結束(這種情況很可能出現),這時為了等待呼叫結果,執行緒依舊會被阻塞。
解決的辦法是用回撥函式,當呼叫結束時會自動呼叫回撥函式
回撥非同步:
public class Foo { static void Main() { Console.WriteLine("**********AsyncInvokeTest**************"); AddHandler handler = new AddHandler(Add); IAsyncResult result = handler.BeginInvoke(1,2,new AsyncCallback(AddComplete),"AsycState:OK"); Console.WriteLine("Do other work... ... ..."); Console.ReadLine(); } static int Add(int a, int b) { Console.WriteLine("Computing "+a+" + "+b+" ..."); Thread.Sleep(3000); Console.WriteLine("Computing Complete."); return a+b; } static void AddComplete(IAsyncResult result) { AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate; Console.WriteLine(handler.EndInvoke(result)); Console.WriteLine(result.AsyncState); } }