2012-08-22 42 views
2

我試圖在後臺線程(BackgroundWorker)中創建一個BitmapImage,但是我的函數只能立即返回null並且不會進入Deployment.Current.Dispatcher.BeginInvoke。當我在UI線程中使用這個函數時,一切都很好。到文件的路徑是正確的(這是一個.JPG圖片)創建BitmapImage的背景

public static BitmapImage convertFileToBitmapImage(string filePath) 
{ 
    BitmapImage bmp = null; 
    Uri jpegUri = new Uri(filePath, UriKind.Relative); 
    StreamResourceInfo sri = Application.GetResourceStream(jpegUri); 

    Deployment.Current.Dispatcher.BeginInvoke(new Action( () => 
     { 

      bmp = new BitmapImage(); 
      bmp.SetSource(sri.Stream); 

     })); 
    return bmp; 
} 

回答

4

的問題是您使用Dispatcher.BeginInvoke將在UI線程上異步運行的任務,沒有一種機制保障,到時候,你從函數返回位圖將被初始化。如果你需要立即初始化,你應該使用Dispatcher.Invoke,這樣就可以同步發生。

更新

錯過了你的標籤爲它是Windows Phone的,然而,同樣的問題仍然存在,你不給你的應用程序有足夠的時間來初始化位圖。您可以使用AutoResetEvent等待在從方法返回之前創建位圖,例如

public static BitmapImage convertFileToBitmapImage(string filePath) 
{ 
    BitmapImage bmp = null; 
    Uri jpegUri = new Uri(filePath, UriKind.Relative); 
    StreamResourceInfo sri = Application.GetResourceStream(jpegUri); 
    AutoResetEvent bitmapInitializationEvt = new AutoResetEvent(false); 
    Deployment.Current.Dispatcher.BeginInvoke(new Action(() => { 
     bmp = new BitmapImage(); 
     bmp.SetSource(sri.Stream); 
     bitmapInitializationEvt.Set(); 
    })); 
    bitmapInitializationEvt.WaitOne(); 
    return bmp; 
} 
+0

在Windows Phone 7.1中沒有Invoke方法,或者你的意思是另一種方法? – igla

+0

@igla啊錯過了你的Windows手機標籤!但是,問題仍然是你的迴歸太快。 – James

+0

很多幫助!好的解決方案 – igla