[英]Firebase Unity - getDownloadURLAsync for multiple images
我正在尝试从 Firebase 检索 2 个图像的下载 url,以便将它们作为字符串传递给另一种方法来下载它们。
对于单个图像,我正在使用此代码:
img1_ref.GetDownloadUrlAsync().ContinueWith((Task<Uri> task) => {
if (!task.IsFaulted && !task.IsCanceled) {
UnityMainThreadDispatcher.Instance().Enqueue(() => UIcontroller.displayImage(task.Result.ToString()));
}
});
效果很好——但我不知道如何获取两个 url,确保我拥有它们,然后将它们传递给下载方法……我正在努力了解 aSync……
收到任何帮助感激不尽!
如果您想使用 Continuations,它相对简单。
首先,我建议将您的原始代码更改为:
img1_ref.GetDownloadUrlAsync().ContinueWithOnMainThread((Task<Uri> task) => {
if (!task.IsFaulted && !task.IsCanceled) {
UIcontroller.displayImage(task.Result.ToString()));
}
});
这使用Firebase 任务扩展以更简洁的方式将您的逻辑移至主线程。
接下来,您可以使用Task.WhenAll创建一个等待多个任务完成的任务:
var task1 = img1_ref.GetDownloadUrlAsync();
var task2 = img2_ref.GetDownloadUrlAsync();
Task.WhenAll(task1, task2).ContinueWithOnMainThread((Task<Uri>[] tasks) => {
if (!task.IsFaulted && !task.IsCanceled) {
// work with tasks here. You can also use IEnumerable<Task<Uri>>
}
});
当然,现在我们可以找点乐子了。 我建议阅读Firebase 中关于线程的这篇文章以获得更多背景知识。
您可以使用@Frank van Puffelen 的回答并执行如下操作:
async void DownloadAsync() {
var task1 = img1_ref.GetDownloadUrlAsync();
var task2 = img2_ref.GetDownloadUrlAsync();
await Task.WhenAll(task1, task2);
// you're on the calling thread here, which is usually the main thread
UIcontroller.displayImage(task1.Result.ToString());
}
或者你可以将这一切移动到协程中以获得更多的 Unity 感知 memory 安全性:
IEnumerator DownloadCoroutine() {
var task1 = img1_ref.GetDownloadUrlAsync();
var task2 = img2_ref.GetDownloadUrlAsync();
yield return new WaitUntil(()=>Task.WhenAll(task1, task2).IsComplete);
// coroutines always run on the main thread, and only if this hasn't been destroyed
UIcontroller.displayImage(task1.Result.ToString());
}
基于Running multiple async tasks and waiting them all to complete那是:
var task1 = img1_ref.GetDownloadUrlAsync();
var task2 = img2_ref.GetDownloadUrlAsync();
await Task.WhenAll(task1, task2);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.