我的應用程序運行CPU重型algorythms來編輯放置在WPF窗口的圖像。我需要在後臺線程中完成版本。但是,嘗試在非UI線程中編輯WritableBitmap的BackBuffer將引發InvalidOperationException。如何在非UI線程中編輯WritableBitmap.BackBuffer?
private WriteableBitmap writeableBitmap;
private void button1_Click(object sender, RoutedEventArgs e)
{
// Create WritableBitmap in UI thread.
this.writeableBitmap = new WriteableBitmap(10, 10, 96, 96, PixelFormats.Bgr24, null);
this.image1.Source = this.writeableBitmap;
// Run code in non UI thread.
new Thread(
() =>
{
// 'Edit' bitmap in non UI thread.
this.writeableBitmap.Lock(); // Exception: The calling thread cannot access this object because a different thread owns it.
// ... At this place the CPU is highly loaded, we edit this.writeableBitmap.BackBuffer.
this.writeableBitmap.Unlock();
}).Start();
}
我看了幾十手冊,所有的人都告訴我做的UI線程後備緩衝版(即MSDN)。
如何在非UI線程中編輯WritableBitmap.BackBuffer,而不進行任何無用的緩衝區複製/克隆?
我不認爲這是正確的做法。這兩個Invoke調用將阻塞的時間比寫入緩衝區所需的時間要長。 – Brannon 2014-02-13 21:28:17
我完全同意像素緩衝區的更新是快速過程的場景。如果緩衝區更新涉及一些昂貴的計算(即比兩個調用調用花費更多),那麼上述應該仍然是一個完全可行的方法。 – LOAS 2014-02-17 14:53:21