/// <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