© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
14 replies
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;
img.Source = image;


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

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


and

Dispatcher.BeginInvoke(() =>
{
    img.Source = image;
});
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."
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 ;
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 ;
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Variable calling from other classes
C#CC# / help
2y ago
❔ ✅ Access variable from another script
C#CC# / help
3y ago
❔ How to access variable from AccessibilityObject ?
C#CC# / help
3y ago
C# Environment variable
C#CC# / help
2y ago