Vis*_*hal 2 c# multithreading windows-phone windows-phone-8
我正在研究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();
}
现在,令人惊讶的部分是我没有在"new BitmapImage()"中得到错误,以防我在其中一个主要函数中执行相同的操作,例如:
public MainPage()
{
    InitializeComponent();
    BitmapImage biImg = new BitmapImage();    // ****** NO ERROR ***********
    T1 = new Thread(ProcessFrames);
    T1.Start();
}
任何人都可以帮助我理解这种行为的原因.我的要求是能够使用预览缓冲区(previewBuffer1)并将其显示在其中一个图像帧中.这需要我在单独的任务中创建一个新的BitmapImage.
只有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;
            });
        }
    }
}