1. 程式人生 > >c#Coroutine協程 WebClient非同步下載靜態資源

c#Coroutine協程 WebClient非同步下載靜態資源

        /// <summary>
        /// 非同步下下載靜態資源
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        IEnumerator DownloadFile(string url)
        {
            bool done = false;
            using (var client = new WebClient())
            {
                client.DownloadStringCompleted 
+= (s, e) => { done = true; results.Add(e.Result); }; client.DownloadStringAsync(new Uri(url)); } while (!done) yield return null; }

這裡的 results 是一個List<string>

用協程批量執行

        IEnumerator DownloadAllAtOnce()
        {
            //Start multiple async downloads and store their handles
            var downloads = new List<CoroutineHandle>();
            downloads.Add(runner.Run(DownloadFile("http://localhost:1323/static/v3.0.0/1106-1.sql")));
            downloads.Add(runner.Run(DownloadFile(
"http://localhost:1323/static/v3.0.0/1106-2.sql"))); //Wait until all downloads are done while (downloads.Count > 0) { yield return null; for (int i = 0; i < downloads.Count; ++i) if (!downloads[i].IsRunning) downloads.RemoveAt(i--); } }

 

協程

        CoroutineRunner runner = new CoroutineRunner();
        const float updateRate = 1f / 30f;
        public void Run2()
        {
            var run = runner.Run(DownloadAllAtOnce());
            while (run.IsRunning)
            {
                runner.Update(updateRate);
            }
        }
CoroutineRunner 和 CoroutineHandle 參考
https://github.com/ChevyRay/Coroutines