2012-08-22 44 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