1

I have code which generates an image doing lots of things, so I run it as async Task. After the generation is completed the image should be displayed in the Image WPF element. But I get System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it.'

BitmapImage? img = await Task.Run(GenerateResultPhoto);
PhotoResult.Source = img; //Exception here
 
private BitmapImage? GenerateResultPhoto()
{
    //Lots of things going there in actual code
    //But any returned BitmapImage is inaccessible
    return new BitmapImage();
}

Using Application.Current.Dispatcher changes nothing:

Application.Current.Dispatcher.Invoke(new Action(() => {
    PhotoResult.Source = img; //Same exception
}));
5
  • So marshal your code/data to the UI thread and run it there? Commented Feb 15, 2024 at 18:45
  • @UweKeim What's the best way to do this? I'm not skilled in C# async, so even my Task approach may be wrong. Commented Feb 15, 2024 at 18:50
  • I do think this is the way to go. Commented Feb 15, 2024 at 18:55
  • 1
    My bad, this actually is a direct duplicate and the cited question has the right answer - you need to Freeze the BitmapSource before returning it outside the worker thread. Commented Feb 15, 2024 at 23:38
  • 1
    @EmperorEto that's what I did and it worked. Commented Feb 18, 2024 at 21:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.