How to edit a WritableBitmap.BackBuffer in non UI thread?

前端 未结 5 785
旧时难觅i
旧时难觅i 2020-12-03 15:37

My application runs CPU-heavy algorythms to edit an Image placed at a WPF window. I need the edition to be done in a background thread. However trying to edit the BackBuffer

5条回答
  •  囚心锁ツ
    2020-12-03 16:20

    You simply can't write to BackBuffer from a non UI thread.

    In addition to what Klaus78 said, i would suggest the following approach:

    1. Perform asynchronous "bitmap editing" code on a separate buffer (e.g. byte[]) in a ThreadPool thread by means of QueueUserWorkItem. Do not create a new Thread every time you need to perform an asynchronous operation. That's what ThreadPool was made for.

    2. Copy the edited buffer by WritePixels in the WriteableBitmap's Dispatcher. No need for Lock/Unlock.

    Example:

    private byte[] buffer = new buffer[...];
    
    private void UpdateBuffer()
    {
        ThreadPool.QueueUserWorkItem(
            o =>
            {
                // write data to buffer...
                Dispatcher.BeginInvoke((Action)(() => writeableBitmap.WritePixels(..., buffer, ...)));
            });
    }
    

提交回复
热议问题