解析C#中委託的同步調用與非同步呼叫(執行個體詳解)

來源:互聯網
上載者:User

委託的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);
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.