委托的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... ... ...
同步調用會阻塞線程,如果是要調用一項繁重的工作(如大量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.
可以看到,主線程并沒有等待,而是直接向下運行了。
但是問題依然存在,當主線程運行到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);
}
}