I have a strange behavior in WPF 4.5 (.net 4.5). I'm using the keywords await and async in order to run long-operations (for example load a big BitmapImage, base for a Image control). The problem is that the awaiter doesn't return to the main UI Thread, because I get teh famous Exception:
The calling thread cannot access this object because a different thread owns it.
Could someone help me?
Here my code:
Event handler of a button:
private void GetExifData_Click(object sender, RoutedEventArgs e)
{
// Async method
(new AnalyzeSingleImage()).RunExif(this);
}
The main method (in a separate class, same assembly)
public async void RunExif(MainWindow win)
{
// here I run correctly code on the main UI Thread
..
..
// ASYNC !!!
BitmapImage bi = await LoadImageAsync(fileName);
Image img = new Image();
img.Source = bi; // *********** HERE I GET THE EXCEPTION *************
..
..
}
The Async method:
private Task<BitmapImage> LoadImageAsync(string fileName)
{
return Task<BitmapImage>.Run(() => LoadImage(fileName));
}
The long time method:
private BitmapImage LoadImage(string fileName)
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(fileName);
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.EndInit();
return bi;
}
Someone could help me please?