Search code examples
c#wpfbitmapsource

Updating bitmapSource - copying one to another


This is my exception

The calling thread cannot access this object because a different thread owns it.

my function get results from a calculation and I want to update an already opened window..

 public override void UpdateResult(BaseMetricResults result)
        {
            var newResults = result as MetricUniformityResults;
            if (newResults == null)
            {
                return;
            }
            DispatcherHelper.UIDispatcher.Invoke(() =>
                {             
                    TopToBottomGraph.CrossSectionPoints.Clear();
                    foreach (var point in newResults.TopToBottomGraph.CrossSectionPoints)
                    {
                        TopToBottomGraph.CrossSectionPoints.Add(point);
                    }

                    newResults.JetMap.Freeze(); //exception here
                    byte[] arr = new byte[(int) (newResults.JetMap.Width*newResults.JetMap.Height*3)];
                    newResults.JetMap.CopyPixels(arr, (int) (newResults.JetMap.Width*3), 0);
                    JetMap = BitmapSource.Create((int) newResults.JetMap.Width, (int) newResults.JetMap.Height, 96, 96,
                                                 PixelFormats.Rgb24, BitmapPalettes.WebPalette, arr,
                                                 (int) (newResults.JetMap.Width*3));
                });
        }

This is my last attempt I'm not sure if I have to freeze the bitmapsource or not...
Anyway newResults.JetMap is BitmapSource, and I have a property named JetMap which is the new BitmapSource, how can I update the old image with the new one?


Solution

  • You need to call Jetmap.Freeze(); right after you create it and not inside the dispatcher, once its its frozen you can set it inside the dispatcher and you wont get an exception