C#多线程EAP与APM风格
说明 同步方法:干完事才返回。 异步方法:启动一件事情,然后就返回。
1、WebClient类的使用
/// /// 同步方法 干完事才返回 /// 异步方法 启动一件事情,然后就返回 /// public static void Main01() { ThreadPool.QueueUserWorkItem((state) => { WebClient wc = new WebClient(); string html = wc.DownloadString("https://www.github.com"); Console.WriteLine(html); }); }
2、EAP风格
EAP风格:基于事件异步编程。缺点:当业务复杂的时候处理比较麻烦,比如Ajax。
/// /// EAP风格 基于事件异步编程 /// 缺点:当业务复杂的时候处理比较麻烦,比如Ajax /// public static void Main02() { WebClient wc = new WebClient(); wc.DownloadStringCompleted += Wc_DownloadStringCompleted; wc.DownloadStringAsync(new Uri("https://www.cnblogs.com/")); } private static void Wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { Console.WriteLine(e.Result); }
3、APM风格
/// /// APM风格 /// public static void Main03() { ThreadPool.QueueUserWorkItem((state) => { using(FileStream fs = File.OpenRead(@"d:\log.txt")) { byte[] buffer = new byte[100]; IAsyncResult res=fs.BeginRead(buffer, 0, buffer.Length,null,null); res.AsyncWaitHandle.WaitOne();//等待执行完成 Console.WriteLine(Encoding.UTF8.GetString(buffer)); } }); }