我正在阅读有关异步等待编程的内容,并且对于想要使函数异步运行的场景感到困惑。例如,我想在我的用户界面上显示图像。因此,在 UI 线程上,我调用一个函数,该函数将从存储中获取图像并将图像应用到 UI 上。
正确的做法是什么?
方法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;
});
}
}
}
方法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;
}
}
最佳答案
由于从磁盘读取文件主要涉及异步 IO,因此您可以利用 Windows Phone 平台提供的各种异步 API。
无需使用Task.Factory.StartNew
或Task.Run
,这意味着根本不需要额外的ThreadPool线程。目前,您的代码并不是真正的异步,请注意,async void
仅适用于顶级事件处理程序,不应在其他情况下使用。
您可以按如下方式利用异步 API:
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;
}
关于c# - 如何使函数异步运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27082190/