BitmapImage:如何在返回图像之前等待 BitmapImage 初始化? (C#.NET)

BitmapImage: How do I wait for BitmapImage to be initialized before returning image? (C# .NET)

我有一种从 zip 文件中打开图像的方法,return将该图像作为 BitmapImage。

public BitmapImage GetImageFromSource()
{
    using (System.IO.Compression.ZipArchive zi = System.IO.Compression.ZipFile.Open(ZipFileLocation, System.IO.Compression.ZipArchiveMode.Read))
    {
        using (Stream source = zi.GetEntry(InternalLocation).Open())
        {
            BitmapImage img = new BitmapImage();
            img.BeginInit();
            img.CacheOption = BitmapCacheOption.OnLoad;
            img.StreamSource = source;
            img.EndInit();

            //sleeping here allows img to complete initialization
            //not sleeping here means img is still blank upon return
            System.Threading.Thread.Sleep(100);

            return img;
        }
    }
}

zip 文件包含大小图像的混合。如果图像很大,img 可能在程序到达 return 之前还没有完成初始化。如果发生这种情况,方法 return 将生成一个空白 BitmapImage。

如果我在 returning 之前睡眠,该方法有效,并且有足够的延迟,大图像成功初始化。

睡眠并不理想,因为它会不必要地锁定主线程,从而减慢程序速度。在 returning BitmapImage 之前如何获取等待初始化完成的方法?

我已经尝试了 IsDownloading 和 DownloadCompleted 事件。 IsDownloading 始终设置为 'true',而 DownloadCompleted 似乎从未被触发。

锁定等待位图加载的主线程并不是很好的做法,框架可能出于某种原因需要延迟加载。这实际上就是这里发生的事情,当加载确实发生时,您已经处理了文件变量。您可以 return 立即获取图像,但您应该将这些变量的处理推迟到文件加载之后:

public BitmapImage GetImageFromSource()
{
    System.IO.Compression.ZipArchive zi = System.IO.Compression.ZipFile.Open(ZipFileLocation, System.IO.Compression.ZipArchiveMode.Read);
    Stream source = zi.GetEntry(InternalLocation).Open();

    BitmapImage img = new BitmapImage();
    img.DownloadCompleted += (s, e) =>
    {
        source.Dispose();
        zi.Dispose();
    };

    img.BeginInit();
    img.CacheOption = BitmapCacheOption.OnLoad;
    img.StreamSource = source;
    img.EndInit();

    return img;
}