简体   繁体   中英

Unable to create BItmapImage inside separate Task

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.

Only the UI thread can instantiate a BitmapImage .

You should try with the Deployment.Current.Dispatcher.BeginInvoke method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM