Reputation: 5104
I was reading about async-await programming and I am confused in a scenario where I want to make a function run asynchronously. For example I want to display an Image on my UI. So, on the UI thread I call a function which would fetch the image from storage and apply the image onto the UI.
What is the correct way to do this?
METHOD 1
private async void SetImage()
{
await Task.Run(() =>
{
byte[] fullViewImageBytes = Utils.GetImageFromStorage(fileName);
if (fullViewImageBytes != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MemoryStream memStream = new MemoryStream(fullViewImageBytes);
BitmapImage image = new BitmapImage();
image.SetSource(memStream);
userImage.Source = image;
});
}
}
}
METHOD 2
private async void SetImage()
{
await Task.Delay(1);
byte[] fullViewImageBytes = Utils.GetImageFromStorage(fileName);
if (fullViewImageBytes != null)
{
MemoryStream memStream = new MemoryStream(fullViewImageBytes);
BitmapImage image = new BitmapImage();
image.SetSource(memStream);
userImage.Source = image;
}
}
Upvotes: 2
Views: 185
Reputation: 149538
As reading a file from disk is mostly about asynchronous IO, you can take advantage of the wide range of asynchronous API provided by the Windows Phone platform.
There is no need to use Task.Factory.StartNew
or Task.Run
, meaning there is no need for an extra ThreadPool thread at all. Currently, your code isn't truly asynchronous, and note that async void
is ment only for top level event handlers and shouldn't be used otherwise.
You can take advantage of the async API as follows:
public async Task<BitmapImage> CreateImageFromFileAsync(string imagePath)
{
StorageFile storageFile = await StorageFile.GetFileFromPathAsync(imagePath);
IRandomAccessStream imageFileStream = await storageFile.OpenReadAsync();
BitmapImage image = new BitmapImage();
await image.SetSourceAsync(imageFileStream);
return image;
}
Upvotes: 4
Reputation: 33381
Something like this:
private static async Task<BitmapImage> GetImageFromStorageAsync(string fileName)
{
var bytes = await Task.Factory
.StartNew((f)=>Utils.GetImageFromStorage((string)f), fileName)
.ConfigureAwait(false);
MemoryStream memStream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.SetSource(memStream);
return image;
}
private async Task SetImage()
{
var image = await GetImageFromStorageAsync(fileName);
userImage.Source = image;
}
Upvotes: 0