为什么 Visual Studio IDE Marshall 在错误的线程上执行静态值,但不在运行时执行?

问题描述

我有一个问题,我的 UWP 用户控件在 (XAML) 设计模式下导致异常,因为线程被编组到错误的线程?我有几个使用相同画笔的控件,它们都使用参考值而不是创建许多新的(相同的)画笔是有道理的。

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

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

在设计时从控件引用时,上述代码导致以下错误System.Exception:应用程序调用一个为不同线程编组的接口。 (来自 HRESULT 的异常:0x8001010E (RPC_E_WRONG_THREAD))

一个简单的解决方案(见下文)是查看控件是否处于设计模式,但想了解为什么它是必要的,是我刚刚在 Visual Studio 中遇到错误还是我的大脑太累了,我错过了一些简单的事情。

注意:我确实理解这意味着它们没有被编组到 UI 线程,但我的问题是为什么 - 当它们在设计器之外正确编组时?

    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;
        }
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)