2

I am working on an imaging application for WP8 (Lumia 920). I am coding in C# in the xaml layer.

I experience problems while trying to create a new BitmapImage object in a separate task, which is expected to use the frames as they are generated by the camera app.

Here is a reduced version of my code:

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

Now, the surprising part is that I don't get the error at "new BitmapImage()" in case I do the same inside one of the main functions, for example:

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

Can anyone help me understand the reason for such a behaviour. My requirement is to be able to use the preview buffer (previewBuffer1) and display it in one of the image frames. This requires me to create a new BitmapImage in the separate task.

4

1 回答 1

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;
            });
        }
    }
}
于 2013-07-17T10:28:36.813 回答