async await

1.BookDAL 有一个产生string 的方法

 public string GetTestString()
        {
            string sReturn = "";
            string[] sList = { "a", "b", "c", "d", "e", "f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z" };
            for (int i=1;i<6;i++)
            {
                Thread.Sleep(1000);
                Random r = new Random();
                int n = r.Next(1, 26);
                sReturn += sList[n];
            }
            return sReturn;
        }

2. MVC HomeController Contact 调用, 跑完需要大概20秒

public ActionResult Contact()
        {
            ViewBag.Start = DateTime.Now;

            BookService BookDAL = new BookService();
            string s1 = BookDAL.GetTestString();
            string s2 = BookDAL.GetTestString();
            string s3 = BookDAL.GetTestString();
            string s4 = BookDAL.GetTestString();

            ViewBag.sValue = s1 + "-" + s2 + "-" + s3 + "-" + s4;

            ViewBag.Message = "Your contact page.";

            ViewBag.End = DateTime.Now;
            return View();
        }

3. MVC HomeController About 用async await,. 它跑完需要大概6秒。

   public async Task<ActionResult> About()
        {
            ViewBag.Start = DateTime.Now;

            ViewBag.Message = "Your application description page.";

            BookService BookDAL = new BookService();
var s1 = GetStringAsync(BookDAL); var s2 = GetStringAsync(BookDAL); var s3 = GetStringAsync(BookDAL); var s4 = GetStringAsync(BookDAL); await Task.WhenAll(s1, s2, s3, s4); ViewBag.sValue = s1.Result + "-" + s2.Result + "-" + s3.Result + "-" + s4.Result; ViewBag.End = DateTime.Now; return View(); } public async Task<string> GetStringAsync(BookService BookDAL) { return await Task.Run(() => { return BookDAL.GetTestString(); }); }

 

你可能感兴趣的:(async await)