【发布时间】:2013-05-06 06:53:09
【问题描述】:
我在一些非 GUI 线程上创建了一个 SolidColorBrush,并想将它传递给一个 GUI 线程来显示它,但我得到了 InvalidOperationException: The calling thread cannot access this object because a different thread owns it.(即使我尝试 Freeze(); 它) .如何将在线程 X 中创建的对象传递给线程 Y?
我知道我可以使用 Dispatcher 在 GUI 线程中创建这个 SolidColorBrush 对象,但这会使一切复杂化...我想在工作线程中创建它。
其他细节:
我在某个静态类中初始化了一些静态委托,以允许从业务层向 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); }
}
初始化(在 GUI 线程中):
Gui.InitializeGuiInterface(_messagesToUserHandler.PrintMessage);
然后在另一个(非 gui)线程中,我使用它:
Gui.Print(new GuiMessage(testDescription) { Foreground = new SolidColorBrush(someColor) });
而GuiMessage 是:
public class GuiMessage {
public string Msg { get; set; }
private SolidColorBrush _foregroundBrush;
public SolidColorBrush Foreground
{
get { return _foregroundBrush; }
set { _foregroundBrush = value; }
}
}
【问题讨论】:
-
您是否尝试将错误消息写给谷歌?它返回我们在这里可能给出的所有答案。
-
我想简短的回答是你不能。所有与 GUI 相关的控件/工件都应在 UI 线程上创建和处理。
-
@I4V:是的,我试过了。谢谢你的建议。
-
@EbenRoux:没有办法吗?没有共享内存(类/C#-API/属性)设施来做到这一点?这不是很奇怪吗?
-
freeze 可以在另一个线程中创建 wpf 资源,然后可以将元素传递给另一个线程或 gui 线程。
标签: c# wpf multithreading