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


 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值