[英]How do I detect a BitmapImage failing to load?
I have the following code to load an image from a url. 我有以下代码从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. 我遇到了最奇怪的错误-当
m_photoPath
是一个在任何浏览器中导致404的网址时,都不会引发异常。 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). 我尝试使用
HttpWebRequest
检查文件是否存在,但是每次我调用[HttpWebRequest instance].GetResponse()
,都会发生非常长的超时(可能是无限的-我没有等着找出[HttpWebRequest instance].GetResponse()
)。 So HttpWebRequest
isn't an option. 因此,
HttpWebRequest
不是一个选择。 Any ideas? 有任何想法吗?
If the image fails to download, the BitmapImage's DownloadFailed event fires. 如果图像下载失败,则触发BitmapImage的DownloadFailed事件。 No exception is thrown.
没有异常被抛出。 You can wire the event up anytime, though it would be pragmatic to do it before calling EndInit!
您可以随时联系事件,尽管在调用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. 这实际上不能由异常处理,因为将来在任何时候都可以放弃下载映像的某些方法-真的没有地方放置try / catch块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.