简体   繁体   中英

How do I detect a BitmapImage failing to load?

I have the following code to load an image from a url. If the url doesn't exist, a placeholder should be loaded instead.

public BitmapImage Image
{
    get
    {
        if (m_image == null)
        {
            try
            {
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.UriSource = new Uri(m_photoPath);
                image.DecodePixelHeight = s_imagePixelHeight;
                image.EndInit();
                m_image = image;
            }
            catch (FileNotFoundException)
            {
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.UriSource = new Uri(c_placeholderImagePath);
                image.DecodePixelHeight = s_imagePixelHeight;
                image.DecodePixelWidth = s_imagePixelWidth;
                image.EndInit();
                m_image = image;
            }
        }
        return m_image;
    }
}

I'm getting the weirdest error - when m_photoPath is a url which causes a 404 in any browser, no exception is thrown. I've tried checking if the file exists by using an HttpWebRequest , but everytime I call [HttpWebRequest instance].GetResponse() , there's a really, really long timeout (possibly infinite - I haven't waited around to find out). So HttpWebRequest isn't an option. Any ideas?

If the image fails to download, the BitmapImage's DownloadFailed event fires. No exception is thrown. You can wire the event up anytime, though it would be pragmatic to do it before calling EndInit!

This couldn't really be handled by an exception, since something could give up on downloading the image at any arbitrary point in the future - there's nowhere really to put a try/catch block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM