0

I'm working on a wpf application. I want to create a FlowDocument object and print it. As the creation step takes some seconds and freeze the UI, I move my code to new thread. The problem is that I need to set an Image in the FlowDocument and need to create Image UIElement, but UI Controls cannot be created in background threads ! I've also tried so many Dispather.Invoke() scenarios, but they catch exception about object owner thread.

I wonder is there any other methods to insert image into the FlowDocument? Or is it possible to create Image UIElement in background thread?

any suggestion would be appreciated.

P.S : Some Example Code =>

BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo;
Image v = new Image() { Source = bitmapImage };
currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v)));




Image v = ((App)Application.Current).Dispatcher.Invoke(new Func<Image>(() =>
{
    BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo;
    return new Image() { Source = bitmapImage};
}));
currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v)));
Mohamad MohamadPoor
  • 1,350
  • 2
  • 14
  • 35

1 Answers1

1

If you don't need to modify the BitmapImage, then you can freeze it and use it on the UI thread.

// Executing on non UI Thread
BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo;
bitmapImage.Freeze(); // Has to be done on same thread it was created on - maybe freeze it in the Singleton instead?

Application.Current.Dispatcher.Invoke(() => {
    // Executing on UI Thread
    Image v = new Image() { Source = bitmapImage };
    currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v)));
});

After chatting with you, what you really needed to do was run your task in a STA thread, since you were making UI controls on it. How to do that? See this answer:

Set ApartmentState on a Task

Community
  • 1
  • 1
J.H.
  • 4,232
  • 1
  • 18
  • 16