'Export png of UserControl in Background Thread

I try to export in Png a WPF UserControl that I made in a background Thread.

The rendering works great in the UI thread, but I can't run my spinner for user waiting correctly because the two controls run in the UI thread.

When I run my code in the backgroung thread I have the following exception :

System.Windows.Markup.XamlParseException: 'The calling thread cannot access this object because a different thread owns it'

I use the following code to create the thread :

 List<Byte[]> images = null;
        Thread thread = new Thread(() =>
        {
            HorizontalViewDesigner horizontalViewDesigner = new HorizontalViewDesigner(true);
            horizontalViewDesigner.ItemsSource = new ObservableCollection<ICanvasSelection>(elements);
            horizontalViewDesigner.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
            horizontalViewDesigner.Arrange(new Rect(new Size(10_000, 10_000)));
            Size size = new Size(1024d, 1024d);
            images = horizontalViewDesigner.GetImages(size);
        });
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
        thread = null;
        return (images);

The exception occurs in the GetImages method on the call of

userControl.UpdateLayout();

It's seems that this method update Dependency Properties from binding.

Any solution ? Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source