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)