创建BitmapImage的背景

时间:2012-08-22 08:06:25

标签: c# windows-phone-7

我正在尝试在后台线程(BackgroundWorker)中创建一个BitmapImage,但我的函数只返回null并且不会进入Deployment.Current.Dispatcher.BeginInvoke。当我在UI线程中使用此功能时,一切都很好。文件的路径是正确的(它是一张.jpg图片)

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

1 个答案:

答案 0 :(得分: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;
}