[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;