Why does the Visual Studio IDE Marshall a static value on the wrong thread but not do it at runtime?

0

I have an issue where my UWP User Controls cause an exception in (XAML) design mode because the thread is marshalled to the wrong thread? What I have is several controls that use the same Brush and it makes sense that they all use reference value rather than creating many new (same) brushes.

internal static Brush DefaultHighlightBrushStore = new SolidColorBrush(Windows.UI.Colors.NavajoWhite);

internal static readonly Brush TransparentBrush = new SolidColorBrush(Windows.UI.Colors.Transparent);

When referenced from a control at desgin time, The above code causes the following error: System.Exception: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

An easy solution (see below) was to see if the control is in design mode but would like to understand why it was necessary, whether I have just encountered a bug in Visual Studio or my Brain is over tired and I am missing something simple.

Note: I do understand that this means they are not being marshalled onto the UI thread but my question is why - when they marshal correctly outside of the designer?

    private static bool DesignMode => Windows.ApplicationModel.DesignMode.DesignModeEnabled;

    private static Brush DefaultHighlightBrushStore = new SolidColorBrush(Windows.UI.Colors.NavajoWhite);
    private static readonly Brush TransparentBrush = new SolidColorBrush(Windows.UI.Colors.Transparent);

    internal static Brush DefaultHighlightBrush
    {
        get
        {
            return DesignMode ? new SolidColorBrush(Windows.UI.Colors.NavajoWhite) : DefaultHighlightBrushStore;
        }

        set
        {
            DefaultHighlightBrushStore = value;
        }
    }

    internal static Brush Transparent
    {
        get
        {
            return DesignMode ? new SolidColorBrush(Windows.UI.Colors.Transparent) : TransparentBrush;
        }
    }
c#
multithreading
visual-studio
uwp
marshalling
asked on Stack Overflow Feb 25, 2021 by Chris Raven • edited Feb 25, 2021 by Chris Raven

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0