C# 无法在单独的任务内创建BItmapImage
我正在为WP8(Lumia 920)开发一个成像应用程序。 我在xaml层用C#编码 我在尝试在单独的任务中创建新的BitmapImage对象时遇到问题,该任务预期将使用相机应用程序生成的帧 以下是我的代码的简化版本:C# 无法在单独的任务内创建BItmapImage,c#,multithreading,windows-phone-8,windows-phone,C#,Multithreading,Windows Phone 8,Windows Phone,我正在为WP8(Lumia 920)开发一个成像应用程序。 我在xaml层用C#编码 我在尝试在单独的任务中创建新的BitmapImage对象时遇到问题,该任务预期将使用相机应用程序生成的帧 以下是我的代码的简化版本: public void ProcessFrames(){ while (true) { dataSemaphore.WaitOne(); if (nFrameCount>0) { Mem
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)并在一个图像帧中显示它。这需要我在单独的任务中创建一个新的位图图像。只有UI线程才能实例化
位图图像
您应该尝试使用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;
});
}
}
}
只有主线程才能创建位图图像。为什么会这样??您知道我如何在这样的限制下工作,并且仍然从字节创建ImageSource吗?