简体   繁体   中英

How can I give an argument to Dispatcher.Invoke?

I'm trying to load a BitmapImage in a background thread and then set the (WPF) image source to this BitmapImage.

I'm currently trying something like this:

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;
        }
    }
}

But I get an InvalidOperationException because the background thread owns the BitmapImage. Is there a way to give the ownership of the BitmapImage or a copy to the UI Thread?

I need to load the bitmap image in the background thread because it may block for a long time.

All work with the DependencyObject should happen in one thread.
Except for frozen instances of Frеezable.

It also makes no sense (in this case) to pass a parameter to Invoke - it is better to use a lambda.

There is also the danger of the Dispatcher self-locking, since you are not checking the flow.

    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;
            }
        }
    }

Objects of type Frеezable do not always allow themselves to be frozen.
But your code is not enough to identify possible problems.
If you fail to freeze, then show how the LoadImage (Uri) method is implemented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM