Search code examples
c#multithreadingdispatcher

Weird Thread exception when using Dispatcher.BeginInvoke in a thread


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();

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.