[STAThread] static void Main(string[] args) { long start=0; long end=0; Class1 c = new Class1(); Console.WriteLine("ready"); start=DateTime.Now.Ticks;
//實例委托 AsyncEventHandler asy = new AsyncEventHandler(c.Event1); //異步調用開始,沒有回調函數和AsyncState,都為null IAsyncResult ia = asy.BeginInvoke(null, null); //同步開始, c.Event2(); //異步結束,若沒有結束,一直阻塞到調用完成,在此返回該函數的return,若有返回值。
asy.EndInvoke(ia);
//都同步的情況。 //c.Event1(); //c.Event2();
end =DateTime.Now.Ticks; Console.WriteLine("時間刻度差="+ Convert.ToString(end-start) ); Console.ReadLine(); } } }
2)下面看有回調函數的WebRequest和WebResponse的異步操作。
using System; using System.Net; using System.Threading; using System.Text; using System.IO;
// RequestState 類用于通過 // 異步調用傳遞數據 public class RequestState { const int BUFFER_SIZE = 1024; public StringBuilder RequestData; public byte[] BufferRead; public HttpWebRequest Request; public Stream ResponseStream; // 創建適當編碼類型的解碼器 public Decoder StreamDecode = Encoding.UTF8.GetDecoder();
public RequestState() { BufferRead = new byte[BUFFER_SIZE]; RequestData = new StringBuilder(""); Request = null; ResponseStream = null; } }
// ClientGetAsync 發出異步請求 class ClientGetAsync { public static ManualResetEvent allDone = new ManualResetEvent(false); const int BUFFER_SIZE = 1024;