Windows Phone - 图像缓存 - 等待下载图像

时间:2012-10-07 12:09:11

标签: c# windows-phone-7 caching

我制作了一个缓存图像的项目。我想在主线程中等待完整的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;
    }

这是DownloadImage函数:

    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  
                }
            }  
        }

    }

2 个答案:

答案 0 :(得分:0)

你有很多方法可以实现你想要的。可以使用async await命令等待,该命令是Visual Studio Async的一部分。 您可以从here下载最新的CTP。 More how to use it.

我个人会使用事件。

答案 1 :(得分:0)