3

我做了一个缓存图像的项目。我想在主线程中等待完整的 DownloadImage 函数,然后返回保存的位图。那可能吗?我做得对吗?

public static ImageSource GetImage(int id)
    {
        BitmapImage bitmap = new BitmapImage();
        String fileName=string.Format("ImageCache/{0}.jpg", id);

        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (!myIsolatedStorage.DirectoryExists("ImageCache"))
            {
                myIsolatedStorage.CreateDirectory("ImageCache");
            }

            if (myIsolatedStorage.FileExists(fileName))
            {
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                {
                    bitmap.SetSource(fileStream);
                }
            }
            else
            {
                DownloadImage(id);
                //HERE - how to wait for end of DownloadImage and then do that below??
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                {
                    bitmap.SetSource(fileStream);
                }
            }
        }
        return bitmap;
    }

这是下载图像功能:

    private static void DownloadImage(Object id)
    {
        WebClient client = new WebClient();
        client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
        client.OpenReadAsync(new Uri(string.Format("http://example.com/{0}.jpg", id)), id);
    }
    private static void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (e.Error == null && !e.Cancelled)
            {
                try
                {
                    string fileName = string.Format("ImageCache/{0}.jpg", e.UserState);
                    IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(fileName);

                    BitmapImage image = new BitmapImage();
                    image.SetSource(e.Result);
                    WriteableBitmap wb = new WriteableBitmap(image);

                    // Encode WriteableBitmap object to a JPEG stream.
                    Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
                    fileStream.Close();

                }
                catch (Exception ex)
                {
                    //Exception handle appropriately for your app  
                }
            }  
        }

    }
4

2 回答 2

0

你有很多方法可以实现你想要的。async await可以使用作为 Visual Studio Async 一部分的命令等待。您可以从这里下载最新的 CTP 。更多如何使用它。

我个人会使用事件。

于 2012-10-08T20:24:43.287 回答
0

这个包含一些细节和代码示例:http ://www.ben.geek.nz/2010/07/one-time-cached-images-in-windows-phone-7/

于 2013-07-03T12:15:58.913 回答