在我的应用程序中,我创建了一个 SerializedBitmapImage 类,它在从互联网下载另一个图像时显示默认图像。它还允许将下载的图像序列化为字节数组,因此不需要在每次应用程序启动时下载图像。
我目前在“Card”类中有一个 SerializedBitmapImage ,它在卡数据下载完成时立即保存:
var resp = await AppData.API.GetCards();
if (resp != null)
{
if (AppData.CardsData == null)
AppData.CardsData = new CardsData();
AppData.CardsData.Update(resp);
AppData.SaveCards();
FillCards();
}
但是,有时在调用 AppData.SaveCards() 时 SerializedBitmapImage 中的图像尚未完成下载,导致图像无法保存。
因此,我正在寻找一种延迟保存直到下载图像的方法。现在,我正在 SerializedBitmapImage 的构造函数中下载图像,如下所示:
Image = new BitmapImage(defaultUri); //set to default while downloading
BitmapImage img = new BitmapImage { CreateOptions = BitmapCreateOptions.None };
img.ImageOpened += (sender, e) => //download successful, set Image to downloaded image
{
Image = sender as BitmapImage;
NotifyPropertyChanged("Image");
};
img.UriSource = downloadUri; //download the image
我在 Serialized BitmapImage 中创建了一个任务来等待图像完成,但我不确定它是否以健康的方式完成其工作。
public async Task WaitForImageDownload()
{
while (Image == null || Image.UriSource.OriginalString == "Assets/MainPage/DefaultCard.png")
await Task.Delay(100); //check again if completed in 100ms
}
然后,在 AppData.SaveCards() 中,我等待所有图像下载完毕,然后再保存卡片:
Task[] tasks = new Task[CardsData.Count];
for (int i = 0; i < CardsData.Count; i++)
tasks[i] = CardsData[i].CardImage.WaitForImageDownload();
await Task.WhenAll(tasks);
这是等待无法等待完成的操作的正确方法吗?或者,有没有办法强制立即下载图像?
感谢您的帮助!
埃利奥特