I’am trying to create a BitmapImage in background thread (BackgroundWorker), but my function only returns at once null and doesn’t enter into Deployment.Current.Dispatcher.BeginInvoke. When I used this function in UI thread, all was fine. The path to file is correct (it’s a .jpg picture)
public static BitmapImage convertFileToBitmapImage(string filePath)
{
BitmapImage bmp = null;
Uri jpegUri = new Uri(filePath, UriKind.Relative);
StreamResourceInfo sri = Application.GetResourceStream(jpegUri);
Deployment.Current.Dispatcher.BeginInvoke(new Action( ( ) =>
{
bmp = new BitmapImage();
bmp.SetSource(sri.Stream);
}));
return bmp;
}
The problem is your using Dispatcher.BeginInvoke which will run the task asynchronously on the UI thread, there is no guarentee that by the time you return from the function the bitmap will be initialized. If you need this to be initialized immediately you should be using Dispatcher.Invoke so it all happens synchronously.
Update
Missed your tag for it being Windows Phone, however, the same problem still exists you are not giving your app enough time to initialize the bitmap. You could perhaps use an AutoResetEvent to wait for the Bitmap to be created before returning from the method e.g.