无法在单独的Task中创建BItmapImage

时间:2013-07-17 10:04:01

标签: c# multithreading windows-phone-8 windows-phone

我正在研究WP8的成像应用程序(Lumia 920)。 我在xaml层中用C#编码。

尝试在单独的任务中创建新的BitmapImage对象时遇到问题,预计会使用相机应用程序生成的帧。

以下是我的代码的简化版本:

public void ProcessFrames(){
    while (true)
    {
        dataSemaphore.WaitOne();
        if (nFrameCount>0)
        {
            MemoryStream ms = new MemoryStream(previewBuffer1);

            BitmapImage biImg = new BitmapImage();  // *******THROWS AN ERROR AT THIS LINE ********
            biImg.SetSource(ms);

            ImageSource imgSrc = biImg as ImageSource;
            capturedFrame.Source = imgSrc;
        }
    }
}

public MainPage()
{
    InitializeComponent();
    T1 = new Thread(ProcessFrames);
    T1.Start();
}

现在,令人惊讶的是我在“新BitmapImage()”中没有得到错误,以防我在其中一个主要功能中执行相同操作,例如:

public MainPage()
{
    InitializeComponent();
    BitmapImage biImg = new BitmapImage();    // ****** NO ERROR ***********
    T1 = new Thread(ProcessFrames);
    T1.Start();
}

任何人都可以帮助我理解这种行为的原因。我的要求是能够使用预览缓冲区(previewBuffer1)并将其显示在其中一个图像帧中。这需要我在单独的任务中创建一个新的BitmapImage。

1 个答案:

答案 0 :(得分:5)

只有UI线程可以实例化BitmapImage

您应该尝试使用Deployment.Current.Dispatcher.BeginInvoke方法:

public void ProcessFrames(){
    while (true)
    {
        dataSemaphore.WaitOne();
        if (nFrameCount>0)
        {
            MemoryStream ms = new MemoryStream(previewBuffer1);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                BitmapImage biImg = new BitmapImage();
                biImg.SetSource(ms);

                ImageSource imgSrc = biImg as ImageSource;
                capturedFrame.Source = imgSrc;
            });
        }
    }
}