C#C
C#3y ago
Max

❔ c# access variable from other thread

I've been searching the web for a while and I cant seem to access a variable like this:

img.Source = image;

where image comes from a different thread (Task.Run(...)). I have tried

img.Dispatcher.Invoke(() => img.Source = image);

and

Dispatcher.BeginInvoke(() =>
{
    img.Source = image;
});


but both do not work.

Error: System.InvalidOperationException: "The calling thread cannot access this object because a different thread owns it."

Full code:

BitmapImage[] BitmapImages = await Task.Run(() =>
{
    BitmapImage[] bitmapImages = new BitmapImage[files.Count];
    int i = 0;
    foreach (string file in files)
    {
        BitmapImage image = new();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.DecodePixelWidth = 200;
        image.UriSource = new Uri(file);
        image.EndInit();

        bitmapImages[i++] = image;
    }

    return bitmapImages;
});

foreach (BitmapImage image in images)
{
    if (image == null)
        return;

    Image img = new();
    img.Source = image;

}

return ;
Was this page helpful?