I'm trying to use MVVM for a Universal Windows project but the interfaces for Storage File complains a lot about using async. The following code sometimes works:
public object Convert(object value, Type targetType, object parameter, string language)
{
var storageFile = value as StorageFile;
return GetImageAsync(storageFile).Result;
}
private static async Task<ImageSource> GetImageAsync(StorageFile storageFile)
{
var bitmapImage = new BitmapImage();
var stream = await storageFile.OpenAsync(FileAccessMode.Read).AsTask().ConfigureAwait(false);
bitmapImage.SetSource(stream);
return bitmapImage;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return null;
}
}
Until I select a new image to load, then I get the error "{"The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"}"
So I tried changing it to use the CoreDispatcher per another thread:
public class FileToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var storageFile = value as StorageFile;
Task<ImageSource> image = null;
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
image = GetImageAsync(storageFile);
image.RunSynchronously();
});
return image.Result;
}
private static async Task<ImageSource> GetImageAsync(StorageFile storageFile)
{
var bitmapImage = new BitmapImage();
var stream = await storageFile.OpenAsync(FileAccessMode.Read).AsTask().ConfigureAwait(false);
bitmapImage.SetSource(stream);
return bitmapImage;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return null;
}
}
NullReferenceException on bitmapimage. This makes absolute sense to me of course - the async dispatcher cedes control to the parent process, image has not been assigned, null reference exception. But I don't know what the right way is!