C#在多个线程之间传输writeablebitmap

时间:2014-04-03 07:30:23

标签: c# wpf multithreading streaming writeablebitmap

我已经搜索了一下这个问题。有一些解决方案,但没有一个解决我的问题。场景是,我在后台线程中获取并处理位图流,并且在每个帧准备好之后,我正在尝试更新MainWindow中的位图。我在这里粘贴关键代码片段来解释这个场景。

UI Thread / MainWindow.xaml.cs

object lockObject = ThreadLockProvider.sharedInstance.LockObject;

lock (lockObject)
{
   WriteableBitmap imageFromBackgroundThread = this.webserver.getForegroundBitmap().Clone();
   this.newImage         = new WriteableBitmap(imageFromBackgroundThread );
   this.IconImage.Source = this.newImage;
}

后台线程/ ImageProcessor.cs

object lockObject = ThreadLockProvider.sharedInstance.LockObject;

lock (lockObject)
{
     // do the image processing tasks with this.foregroundBitmap                        
}

当我执行代码时,我在主线程中收到错误 - '调用线程无法访问此对象,因为另一个线程拥有它。'无法弄清楚原因。任何人都可以帮我解决问题吗?我已经通过了这个链接 -

Trouble with locking an image between threads

C# threading bitmap objects / picturebox

Writeablebitmap exception when having multiple threads

感谢。

3 个答案:

答案 0 :(得分:2)

在UI线程中使用位图之前,必须先调用Freeze。并且您只能通过其Dispatcher访问Image控件:

newImage = new WriteableBitmap(imageFromBackgroundThread);
newImage.Freeze();
IconImage.Dispatcher.Invoke(new Action(() => IconImage.Source = newImage));

答案 1 :(得分:0)

尝试替换此行

this.IconImage.Source = this.newImage;

使用以下代码

Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
    new Action(delegate()
    {
        this.IconImage.Source = this.newImage;
    }));

答案 2 :(得分:0)

尝试像这样更新UI对象:

Application.Current.Dispatcher.Invoke(()=> {//此处更新UI对象});