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