var client = new WebClient();
var bytes = client.DownloadData(webUrl); <-- NOT null
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
BitmapImage img = new BitmapImage();
img.BeginInit();
img.StreamSource = new MemoryStream(bytes); <-- null
img.EndInit();
img_DownloadCompleted(img, webUrl);
}));
Run Code Online (Sandbox Code Playgroud)
上述代码在线程中执行,以避免阻止UI.
我试图将图像从互联网下载到BitmapImage对象中.图像下载正确,但当我尝试在我的UI(使用Dispatcher.Invoke)中使用它时,我收到此错误消息:The calling thread cannot access this object because a different thread owns it.
所以我添加了在UI线程上创建图像的代码.但是现在,当代码到达<-- null变量bytes所指示的行时突然变为空.在执行进入匿名函数之前它不为null.(我查看了调试器)
有人知道为什么吗?谷歌不是很有帮助.
更改变量类型的bytes,以var不作任何区别.