gpt4 book ai didi

c# - 无法在单独的任务中创建 BItmapImage

转载 作者:行者123 更新时间:2023-12-03 12:49:22 25 4
gpt4 key购买 nike

我正在开发 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;
});
}
}
}

关于c# - 无法在单独的任务中创建 BItmapImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17696849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com