我在一些非GUI線程上創建了一個SolidColorBrush
,並且想將它傳遞給一個GUI線程來顯示它,但是我得到了InvalidOperationException
:The calling thread cannot access this object because a different thread owns it.
(即使我嘗試了Freeze();
它)。我如何傳遞是在線程X創建線程ÿ對象?如何傳遞是在線程X中創建一個WPF對象,線程Y'
我知道我可以在GUI線程中使用Dispatcher
創建此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);
然後在另一個(non-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; }
}
}
您是否嘗試將錯誤消息寫入Google?它返回我們可能給出的所有答案。 – I4V 2013-05-06 06:55:23
我想簡短的答案是你不能。應該在UI線程上創建和處理所有與GUI相關的控件/工件。 – 2013-05-06 06:59:48
@ I4V:是的,我試過了。謝謝你的建議。 – Tar 2013-05-06 07:11:39