如何将在线程X中创建的WPF对象传递给线程Y?

Tar*_*Tar 8 c# wpf multithreading

我创建了一个SolidColorBrush非GUI线程,并希望将其传递给GUI线程来显示它,但我得到InvalidOperationException:( The calling thread cannot access this object because a different thread owns it.即使我尝试Freeze();它).如何将在线程X中创建的对象传递给线程Y?

我知道我可以SolidColorBrush在GUI线程中创建这个对象Dispatcher,但这会使一切变得复杂......我想在工作线程中创建它.


额外细节:

我在一些静态类中初始化一些静态委托,以允许从业务层向GUI发送消息:

public static class Gui{
    private static PrintMethodDelegate _printMethod;
    public static void InitializeGuiInterface(PrintMethodDelegate printMethod){
        _printMethod = printMethod;
    }
    public static void Print(GuiMessage data) { _printMethod(data); }
}
Run Code Online (Sandbox Code Playgroud)

初始化(在GUI线程中):

Gui.InitializeGuiInterface(_messagesToUserHandler.PrintMessage);
Run Code Online (Sandbox Code Playgroud)

然后在另一个(非gui)线程中,我使用它:

Gui.Print(new GuiMessage(testDescription) { Foreground = new SolidColorBrush(someColor) });
Run Code Online (Sandbox Code Playgroud)

同时GuiMessage是:

public class GuiMessage {
    public string Msg { get; set; }

    private SolidColorBrush _foregroundBrush;
    public SolidColorBrush Foreground
    {
        get { return _foregroundBrush; }
        set { _foregroundBrush = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

dow*_*for 8

如果你冻结它们,你可以在另一个线程中创建wpf资源,之后元素可以传递给另一个线程或gui线程.请记住,只能通过复制和使用该副本来修改一次冻结的对象.您无法冻结附加了绑定或动画的对象.