【发布时间】:2017-03-21 18:24:13
【问题描述】:
我正在学习 c# 和 wpf。 我尝试从网络加载一个 img 并将其绑定到一个 Image,但失败了。
它说“调用线程无法访问这个对象,因为另一个线程拥有它”
但我已经使用了“Img1.Dispatcher.Invoke()”,为什么又出现这个异常?
private void Window_ContentRendered(object sender, EventArgs e)
{
Img1.Dispatcher.Invoke(async () =>
{
Img1.Source = await DownloadImg("http address");
});
}
private Task<ImageSource> DownloadImg(string url)
{
return Task.Run(() =>
{
ImageSource source = new BitmapImage(new Uri(url));
return source;
});
}
【问题讨论】:
-
从重复问题的答案中,您可以将 BitmapFrame 替换为 BitmapImage。重要的是先异步下载图片缓冲区,然后创建并返回一个冻结的BitmapSource。
标签: wpf async-await