Question

I'm running a pretty time-consuming method in a thread, and one of the things it does, is if there is no image available it sets a grid named Background's background to a solid color. Here's how that snippet looks:

SolidColorBrush scb = new SolidColorBrush();
scb.Color = Color.FromRgb(21, 21, 21);
Dispatcher.BeginInvoke(new Action(() => Background.Background = scb)); 

But I always get errors at this place saying "Cannot use a DependencyObject that belongs to a different thread than its parent Freezable"

Does anyone know why this is happening? The Dispatcher should make this problem go away, right?

Here's how I am calling the method by the way (if needed)

Thread BGthread = new Thread(HandleBackgrounds);
BGthread.Start();
Was it helpful?

Solution

SolidColorBrush is a dependency object - and you're creating it in the non-UI thread, then trying to use it in the UI thread. Try this instead:

Action action = () =>
{
    SolidColorBrush scb = new SolidColorBrush(Color.FromRgb(21, 21, 21));
    Background.Background = scb;
};
Dispatcher.BeginInvoke(action);

Or of course just in one statement:

Dispatcher.BeginInvoke((Action (() =>
    Background.Background = new SolidColorBrush(Color.FromRgb(21, 21, 21)))));

Either way, you're creating the SolidColorBrush in the action that you're passing to the dispatcher.

OTHER TIPS

A Brush is a DispatcherObject, and as such it has a thread affinity - it belongs to the thread that created it, and normally can only be used by it.

However, WPF has a sub-class of dispatcher objects, called Freezables, for which you can remove the thread affinity by making them read-only. Brushes are freezable, so you can create one on a thread and pass it to another:

var scb = new SolidColorBrush(Color.FromRgb(21, 21, 21));
scb.Freeze();
Dispatcher.BeginInvoke(new Action(() => Background.Background = scb)); 

This can be useful if you're creating a brush in a view model that's not created on a UI thread. Another common use case is decoding images on a different thread, which can improve performance (ImageSource is also a freezable).

Freezing freezables is also considered a performance optimization, so use it whenever possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top