【问题标题】:WPF:The calling thread cannot access this object because a different thread owns it [duplicate]WPF:调用线程无法访问此对象,因为不同的线程拥有它[重复]
【发布时间】: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


【解决方案1】:

您无法访问图像,因为您必须在 UI 线程中执行此操作。您可以创建一个私有字段,并在您的构造函数中使用_dispatcher = Dispatcher.CurrentDispatcher 设置它。在您的Task 中,您必须使用此调度程序并调用方法Invoke 来设置您的图像。 更多信息:Dispatcher.CurrentDispatcher

【讨论】:

    猜你喜欢
    • 2014-02-13
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多