I'm writing a class that can asynchronously load BitmapImage from a local file or a web link. I wait for BitmapImage to end downloading by using the DownloadCompleted and DownloadFailed event, then freeze it and pass it from worker thread to UI thread. But my code doesn't work, if I set web link as BitmapImage's UriSource, those event handlers will never be called. However, I notice that the WPF Image control can be notified when its source(BitmapImage) downloads completely and then show it, so I guess there must be some ways I dont't know to get notfied when a BitmapImage finish loading. Does anyone knows? Here is my code:
BitmapImage image = await Task.Run(async () =>
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = uri;
image.EndInit();
if (image.IsDownloading)
{
using EventWaitHandle handle = new EventWaitHandle(
false, EventResetMode.ManualReset);
void RemoveEventHandler()
{
image.DownloadCompleted -= OnDownloadCompleted;
image.DownloadFailed -= OnDownloadFailed;
}
void OnDownloadCompleted(object? sender, EventArgs args)
{
handle.Set();
RemoveEventHandler();
}
void OnDownloadFailed(object? sender, EventArgs args)
{
handle.Set();
RemoveEventHandler();
}
image.DownloadCompleted += OnDownloadCompleted;
image.DownloadFailed += OnDownloadFailed;
await Task.Run(handle.WaitOne);
}
image.Freeze();
return image;
});