在棱镜中的其他模块中订阅事件



在我的 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.

最新更新