订阅的事件在不同的模块中的棱镜
问题描述:
在我LoginModule
在一个视图模型我分派事件:订阅的事件在不同的模块中的棱镜
void LoginUpdate(object sender, EventArgs e)
{
_eventAggregator.GetEvent<LoginStatusEvent>().Publish(_status);
}
在EventModule
:
public class LoginStatusEvent : PubSubEvent<LoginStatus>
{
}
然后我试图订阅它在不同的模块:
public class EventModule : IModule
{
IRegionManager _regionManager;
IEventAggregator _eventAggregator;
private SubscriptionToken subscriptionToken;
private bool isLoggedIn { get; set; }
public EventModule(IEventAggregator eventAggregator, IRegionManager regionManager)
{
_regionManager = regionManager;
_eventAggregator = eventAggregator;
LoginEventsListener();
}
public void Initialize()
{
}
public void LoginEventsListener()
{
LoginStatusEvent loginStatusEvent = _eventAggregator.GetEvent<LoginStatusEvent>();
if (subscriptionToken != null)
{
loginStatusEvent.Unsubscribe(subscriptionToken);
}
subscriptionToken = loginStatusEvent.Subscribe(LoginStatusEventHandler, ThreadOption.UIThread, false);
}
public void LoginStatusEventHandler(LoginStatus loginStatus)
{
Trace.WriteLine(">> Got it!!");
}
}
但是,LoginStatusEventHandler
永远不会被解雇,我也没有收到任何错误。
答
当订阅事件时,OP没有保持订阅者参考,因此在某一时刻,类没有任何参考并且由GC收集。
所以在这种情况下,它将与True
标志一起使用到Subscribe
方法中。
由于@Haukinger权指出:
Module instance lifetime is short-lived by default. After the Initialize method is called during the loading process, the reference to the module instance is released. If you do not establish a strong reference chain to the module instance, it will be garbage collected. This behavior may be problematic to debug if you subscribe to events that hold a weak reference to your module, because your module just "disappears" when the garbage collector runs.
你在哪里定义事件?发布者和订阅者都需要引用完全相同的类型。 – Haukinger
事件在'EventModule'中定义,在'LoginModule'中触发,我试图在'EventModule'中订阅它 – keeg
它是否与'订阅'方法中的'真正'标志一起工作? – galakt