我如何向 Dispatcher.Invoke 提供参数?

时间:2021-06-03 09:58:09

标签: c# wpf multithreading bitmapimage invalidoperationexception

我正在尝试在后台线程中加载 BitmapImage,然后将 (WPF) 图像源设置为此 BitmapImage。

我目前正在尝试这样的事情:

public void LoadPicture()
{
    Uri filePath = new Uri(Directory.GetCurrentDirectory() + "/" + picture.PictureCacheLocation);
    if (Visible && !loaded)
    {
        if (File.Exists(filePath.AbsolutePath) && picture.DownloadComplete)
        {
            BitmapImage bitmapImage = LoadImage(filePath.AbsolutePath);
            image.Dispatcher.Invoke(new Action<BitmapImage>((btm) => image.Source = btm), bitmapImage);

            loaded = true;
        }
    }
}

但我得到一个 InvalidOperationException,因为后台线程拥有 BitmapImage。 有没有办法将 BitmapImage 的所有权或副本赋予 UI 线程?

我需要在后台线程中加载位图图像,因为它可能会阻塞很长时间。

1 个答案:

答案 0 :(得分:0)

DependencyObject 的所有工作都应该在一个线程中进行。
Freezable 的冻结实例除外。

将参数传递给 Invoke 也是没有意义的(在这种情况下) - 最好使用 lambda。

还有 Dispatcher 自锁的危险,因为您没有检查流量。

    public void LoadPicture()
    {
        Uri filePath = new Uri(Directory.GetCurrentDirectory() + "/" + picture.PictureCacheLocation);
        if (Visible && !loaded)
        {
            if (File.Exists(filePath.AbsolutePath) && picture.DownloadComplete)
            {
                BitmapImage bitmapImage = LoadImage(filePath.AbsolutePath);

                bitmapImage.Freeze();

                if (image.Dispatcher.CheckAccess())
                    image.Source = bitmapImage;
                else
                    image.Dispatcher.Invoke(new Action(() => image.Source = bitmapImage));

                loaded = true;
            }
        }
    }

Frеezable 类型的对象并不总是允许自己被冻结。
但是您的代码不足以识别可能的问题。
如果冻结失败,请展示 LoadImage (Uri) 方法是如何实现的。

相关问题