使用异步对Windows Phone 7的等待(using async await on Windo

2019-10-18 04:49发布

写这asynchronus负载的BitmapImage的代码。

public async void AsyncLoadPhotoNotesFromIsolatedStorage()
{
    IsolatedStorageSettings appStorageSettings = IsolatedStorageSettings.ApplicationSettings;
    if (appStorageSettings.Count > 0)
    {
        var loadedPhotoNotes = new ObservableCollection<PhotoNote>();
        foreach (Object obj in appStorageSettings.Values)
        {
            var tempPhotoNote = (PhotoNote) obj;
            BitmapImage bitmapImage = null;
            Stream imageStream = await LoadImageAsync(tempPhotoNote.Id);
            if (imageStream != null)
            {   
                bitmapImage = new BitmapImage();
                bitmapImage.SetSource(imageStream);
            }

            tempPhotoNote.Picture = bitmapImage;
            loadedPhotoNotes.Insert(0, tempPhotoNote);
        }
        //loadedPhotoNotes.Reverse();
        PhotoNotes = loadedPhotoNotes;
    }
}

方法LoadImageAsync:

private Task<Stream> LoadImageAsync(string fileName)
{
    return Task.Factory.StartNew(() =>
        {
            if (fileName == null)
            {
                throw new ArgumentException("one of parameters is null");
            }

            Stream fileStream = null;

            using (var appStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (appStorageFile.FileExists(fileName))
                {
                    fileStream = appStorageFile.OpenFile(fileName, FileMode.Open, FileAccess.Read);
                }
            }
            return fileStream;
        });
}

该编译器会发出以下错误:

  • 无效标记“无效”的类或接口方法内
  • 在管线Stream imageStream = await LoadImageAsync(tempPhotoNote.Id); 需要“;” 之后await LoadImageAsync
文章来源: using async await on Windows Phone 7