这是一个异步小例子,使用VS新建控制台程序就可以实现,希望对各位理解异步编程有帮助,
C# 提供了两个关键字async、await来是实现异步编程。
一、创建一个请求地址
例如: http://dazhaozhao.com/get.php , 访问这个地址,最少需要1秒的时间响应,为啥呢,因为
这个脚本文件里面就写了两行代码,其中 sleep(1); 表示延迟1秒。
sleep(1);echo time();
二、做两个方法,一个同步调用,一个异步调用
利用HttpClient库,发起http get请求,访问第一步的网址,返回一个时间戳
static readonly HttpClient client = new HttpClient(); static async Task<string> GetAsync(string url) { var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); //Thread.Sleep(3000); return await response.Content.ReadAsStringAsync(); } static string Get(string url) { return client.GetStringAsync(url).Result; }
三、计算执行时间
使用TimeSpan类,计算执行时间
TimeSpan start = new TimeSpan(DateTime.Now.Ticks);//do something//记录结束时间TimeSpan end = new TimeSpan(DateTime.Now.Ticks);//计算时间间隔,求出调用接口所需要的总秒数TimeSpan ts = end.Subtract(start).Duration();Console.WriteLine(ts.TotalSeconds);
四、分别调用异步和同步
同步调用
TimeSpan start = new TimeSpan(DateTime.Now.Ticks); var url = "http://dazhaozhao.com/get.php"; var str1 = Get(url); var str2 = Get(url); var str3 = Get(url); Console.WriteLine(str1); Console.WriteLine(str2); Console.WriteLine(str3); //记录结束时间 TimeSpan end = new TimeSpan(DateTime.Now.Ticks); //计算时间间隔,求出调用接口所需要的总毫秒数 TimeSpan ts = end.Subtract(start).Duration(); Console.WriteLine(ts.TotalSeconds);
执行时间:
异步调用
TimeSpan start = new TimeSpan(DateTime.Now.Ticks);var url = "http://dazhaozhao.com/get.php";var str1 = GetAsync(url);var str2 = GetAsync(url);var str3 = GetAsync(url);Console.WriteLine(str1.Result);Console.WriteLine(str2.Result);Console.WriteLine(str3.Result);//记录结束时间TimeSpan end = new TimeSpan(DateTime.Now.Ticks);//计算时间间隔,求出调用接口所需要的总毫秒数TimeSpan ts = end.Subtract(start).Duration();Console.WriteLine(ts.TotalSeconds);
执行结果:
五、完整代码
using System;using System.Net.Http;using System.Threading.Tasks;namespace AwaitTest{ class Program { static readonly HttpClient client = new HttpClient(); static async Task<string> GetAsync(string url) { var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); //Thread.Sleep(3000); return await response.Content.ReadAsStringAsync(); } static string Get(string url) { return client.GetStringAsync(url).Result; } static void Main(string[] args) { TimeSpan start = new TimeSpan(DateTime.Now.Ticks); var url = "http://dazhaozhao.com/get.php"; var str1 = Get(url); var str2 = Get(url); var str3 = Get(url); Console.WriteLine(str1); Console.WriteLine(str2); Console.WriteLine(str3); //var str1 = GetAsync(url); //var str2 = GetAsync(url); //var str3 = GetAsync(url); //Console.WriteLine(str1.Result); //Console.WriteLine(str2.Result); //Console.WriteLine(str3.Result); //记录结束时间 TimeSpan end = new TimeSpan(DateTime.Now.Ticks); //计算时间间隔,求出调用接口所需要的总秒数 TimeSpan ts = end.Subtract(start).Duration(); Console.WriteLine(ts.TotalSeconds); } }}
来源地址:https://blog.csdn.net/mrtwenty/article/details/126304181