博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c#Coroutine协程 WebClient异步下载静态资源
阅读量:5153 次
发布时间:2019-06-13

本文共 1648 字,大约阅读时间需要 5 分钟。

///         /// 异步下下载静态资源        ///         ///         /// 
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
(); 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
 

 

转载于:https://www.cnblogs.com/rdscfh/p/10138480.html

你可能感兴趣的文章