c#-异步编程-异步模式web
using System; using System.IO; using System.Net; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp19 { class Program { private const string url = "http://www.baidu.com"; static async Task Main(string[] args) { Console.WriteLine("Hello World!"); //fun(); //fun2(); //fun3(); await fun4(); Thread.Sleep(8000); } // 同步调用 static void fun() { using (var client = new WebClient()) { string content = client.DownloadString(url); Console.WriteLine(content.Substring(0,100)); } Console.WriteLine(); } // 异步模式 static void fun2() { WebRequest r = WebRequest.Create(url); IAsyncResult result = r.BeginGetResponse(ReadResponse, null); void ReadResponse(IAsyncResult ar) { using (WebResponse response = r.EndGetResponse(ar)) { Stream strenm = response.GetResponseStream(); var reader = new StreamReader(strenm); string content = reader.ReadToEnd(); Console.WriteLine(content.Substring(0, 100)); Console.WriteLine(); } } } // 事件模式 static void fun3() { using (var client = new WebClient()) { client.DownloadStringCompleted += (sender, e) => { Console.WriteLine(e.Result.Substring(0, 100)); }; client.DownloadStringAsync(new Uri(url)); Console.WriteLine(); } } // 基于任务的异步模式 static async Task fun4() { using (var client = new WebClient()) { string content = await client.DownloadStringTaskAsync(url); Console.WriteLine(content.Substring(1, 100)); Console.WriteLine(); } } } }
二 同步上下文
使用 async 和 await 关键字以后,通常就会到了当前的线程,一般是ui线程,可是若是执行玩以后,不须要进行uic操做,也能够不进入ui线程,直接在原来的线程,出来。但须要金属设置,由于默认的设置 是会跳转到uix线程的。
continueOnCapturedContext设置为fase就表示不用切换到同步上下文,这样执行的会更快一点。编程