I am trying to change an image Source in WPF and it throws a "System.InvalidOperationException" exception ('The calling thread cannot access this object because a different thread owns it.'), now, I tried to put the code in a Application.Current.Dispatcher.Invoke(Action) block but it still throws the error, it is probably relevant that I am trying to change the image from an async method as follows:
// Calling ChangeImage here
public async void LocalKill()
{
for (int i = 0; i < 12; i++)
{
sprite.ChangeImage("@$\"Resources\\Images\\Player\\PlayerDeath{i % 2 + 1}.png\"");
await Task.Delay(1000 / 10);
}
}
// In "Sprite" class
public void ChangeImage(string imagePath)
{
var bitmap = BitmapFromPath(imagePath);
// UI Objects need to be changed in an STA thread
Application.Current.Dispatcher.Invoke(() => image.Source = bitmap);
}
I tried changing the image source, expected it to change the image visually but instead it threw the error