2012-10-07 40 views
3

我做了一個項目來緩存圖像。我想在主線程中等待完整的DownloadImage函數,然後返回保存的位圖。那可能嗎? 我是否正確地做到了?Windows Phone - 圖像緩存 - 等待下載圖像

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

    } 

回答

0

你有很多的方式來實現你想要的。可以使用屬於Visual Studio Async的一部分的async await命令等待。 您可以從here下載最新的CTP。 More how to use it.

我個人會使用事件。

+0

謝謝您的回答。 當我嘗試使用異步等待時,我得到轉換任務到ImageSource的錯誤。 你能給我一個例子如何正確地做到這一點?或更好,如果你會寫一些事情如何使用事件做到這一點?使用(IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName,FileMode.Open,FileAccess.Read)) – bmit

+0

bitmap.SetSource(fileStream); } 到client_OpenReadCompleted的末尾,你很好。 –

+0

但是我不能返回位圖作爲'public static ImageSource GetImage(int id)'的返回' – bmit