ASP.NET - 非同步處理 (三)

  • 5363
  • 0

此篇簡單介紹.ASP NET中的asyncawait


 

主程式 

using System;
using System.Net;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadDay3
{
    //async 與 await
    //    本文將透過一個範例的修改過程來示範如何將原本的同步呼叫的程式碼改成非同步的版本。
    //    透過這篇文章,你將了解 C# 的 async 與 await 關鍵字的用法以及非同步呼叫的執行流程。
    class Program
    {
        private static System.Timers.Timer _timer;
        private static double i = 0;
        //輸出 相關訊息 與當前的執行緒ID
        static void ShowThreadInfo(int num, string msg)
        {
            Console.WriteLine("({0}) T{1}: {2} , 時間: {3}",
                num,Thread.CurrentThread.ManagedThreadId,msg,i.ToString("g"));
        }

        static void Main(string[] args)
        {
            _timer = new System.Timers.Timer();
            _timer.Interval=1;
            _timer.Elapsed += _timer_Elapsed;
            _timer.Enabled=true;
            _timer.Start();
            

            ShowThreadInfo(1, "正要起始非同步工作 MyDownloadPageAsync()。");
            // 接收方法回傳的 task
            Task<string> task = MyDownloadPageAsync("http://huan-lin.blogspot.com");
            ShowThreadInfo(3, "已經起始非同步工作 MyDownloadPageAsync(),但尚未取得工作結果。");
            // 此行是等待 task 回傳後 才繼續往下執行
            string content = task.Result;
            ShowThreadInfo(5, "已經取得 MyDownloadPageAsync() 的結果。");
            Console.WriteLine("網頁內容總共為 {0} 個字元。", content.Length);

            Console.ReadLine();
            _timer.Close();
            _timer.Dispose();
        }

        private static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            i+=0.1;
        }

        //建立非同步方法(告知NET此方法為非同步)
        /// <summary>
        /// 此為非同步方法最主要就是在需要等待的程序給予該程序新的執行緒後
        /// 返回呼叫端等到該執行緒執行完畢後才繼續往下走
        /// </summary>
        static async Task<string> MyDownloadPageAsync(string url)
        {
            ShowThreadInfo(2, "正要呼叫 WebClient.DownloadStringTaskAsync()");

            var webClient = new WebClient();
            // 使用 webClient 的非同步方法 該方法會在執行到 await 時 返回呼叫端
            Task<string> task = webClient.DownloadStringTaskAsync(url);
            // 該方法真正使用 非同步執行的地方 此時會產生新的執行緒
            string content = await task;
            //string content2 = await webClient.DownloadStringTaskAsync(url);
            ShowThreadInfo(4, "已經取得 WebClient.DownloadStringTaskAsync()");
            return content;
        }
    }
}

 

 


多多指教!! 歡迎交流!!

你不知道自己不知道,那你會以為你知道