欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解析C#中委托的同步調(diào)用與異步調(diào)用(實(shí)例詳解)

 更新時(shí)間:2013年05月18日 11:59:56   作者:  
本篇文章是對(duì)C#中委托的同步調(diào)用與異步調(diào)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
委托的Invoke方法用來進(jìn)行同步調(diào)用。同步調(diào)用也可以叫阻塞調(diào)用,它將阻塞當(dāng)前線程,然后執(zhí)行調(diào)用,調(diào)用完畢后再繼續(xù)向下進(jìn)行。
同步調(diào)用的例子:
復(fù)制代碼 代碼如下:

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;
 }
}運(yùn)行結(jié)果:
**********SyncInvokeTest**************
Computing 1 + 2 ...
Computing Complete.
Do other work... ... ...

同步調(diào)用會(huì)阻塞線程,如果是要調(diào)用一項(xiàng)繁重的工作(如大量IO操作),可能會(huì)讓程序停頓很長(zhǎng)時(shí)間,造成糟糕
的用戶體驗(yàn),這時(shí)候異步調(diào)用就很有必要了。
異步調(diào)用不阻塞線程,而是把調(diào)用塞到線程池中,程序主線程或UI線程可以繼續(xù)執(zhí)行。
委托的異步調(diào)用通過BeginInvoke和EndInvoke來實(shí)現(xiàn)。
異步調(diào)用:
復(fù)制代碼 代碼如下:

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;
 }
}運(yùn)行結(jié)果: **********AsyncInvokeTest**************
Do other work... ... ...
Computing 1 + 2 ...
Computing Complete.

可以看到,主線程并沒有等待,而是直接向下運(yùn)行了。
但是問題依然存在,當(dāng)主線程運(yùn)行到EndInvoke時(shí),如果這時(shí)調(diào)用沒有結(jié)束(這種情況很可能出現(xiàn)),這時(shí)為了等待調(diào)用結(jié)果,線程依舊會(huì)被阻塞。
解決的辦法是用回調(diào)函數(shù),當(dāng)調(diào)用結(jié)束時(shí)會(huì)自動(dòng)調(diào)用回調(diào)函數(shù)
回調(diào)異步:
復(fù)制代碼 代碼如下:

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);
 }
}

相關(guān)文章

最新評(píng)論