[英]How to make an eventlistener in a UI thread to listen to an event from another UI thread started from the first thread?
我試圖尋找這個問題的解決方案已經有一段時間了,但我發現的任何東西都無法解決我的問題。
我有兩個UI線程,Window A和Window B,在單個實例應用程序中,B創建並從A開始。當我嘗試在A中添加一個事件監聽器來監聽B是否可見時,我得到一個System.Threading.Tasks.dll中的NullReferenceException,注釋為“ 對象引用未設置為對象的實例。 ”。 我試圖使用Dispatcher而沒有任何運氣。 這是我的代碼的模擬(兩個類都在同一名稱空間中):
public partial class A : Window
{
private B _b;
private Thread _bThread;
private Dispatcher _bDispatcher;
public A ()
{
InitializeComponent();
_bThread = new Thread(() =>
{
try
{
_bDispatcher = Dispatcher.CurrentDispatcher;
_b = new B();
Dispatcher.Run();
}
catch (Exception ex)
{
Logger.Log(ex.message);
}
});
_bThread.SetApartmentState(ApartmentState.STA);
_bThread.Start();
_b.VisibleChanged+= _b_VisibleChanged; // <= if this line is removed the program can start, but with this line I get the exception and the program crasches..
}
private void _b_VisibleChanged(object sender, EventArgs e)
{
// change margin values on A..
}
}
public partial class B : Window
{
private static EventHandlerList Events = new EventHandlerList();
private static readonly object EventVisibleChanged = new object();
public B ()
{
InitializeComponent();
// other stuff
}
private void Window_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
TriggerOnVisibleChanged();
}
#region Triggers
private void TriggerOnVisibleChanged()
{
((EventHandler<EventArgs>)Events[EventVisibleChanged])?.Invoke(this, null);
}
#endregion
#region Event add/remove handlers
public event EventHandler<EventArgs> VisibleChanged
{
add
{
Events.AddHandler(EventVisibleChanged, value);
}
remove
{
Events.RemoveHandler(EventVisibleChanged, value);
}
}
#endregion
}
我不知道我做錯了什么,我不知道如何做這項工作,有人可以幫助我嗎?
PS。 這是為了wpf,而不是Forms .. DS。
PS2。 我知道我沒有必要創建自己的事件和觸發器,可能只是在窗口B中使用了IsVisibleChanged事件,但我嘗試了相同的結果.DS。
我不相信你想要什么是可能的,因為WPF使用一個堅持線程親和力的“公寓”模型,即線程不能相互交互。
此外,您可能會更嚴格地陷入此陷阱......正如文章“具有線程親和力的WPF對象派生自Dispatcher對象”中所述。
編輯:為什么在多線程中? 也許您正在尋找的是RoutedEventHandler(在子窗口中定義)...請參閱此SO帖子以獲取示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.