订阅Prism中不同模块中的事件

时间:2016-06-21 05:13:09

标签: c# mvvm prism

在我的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永远不会被解雇,我没有收到任何错误。

1 个答案:

答案 0 :(得分:1)

OP在订阅活动时没有保留订阅者参考,因此在一刻中,类没有任何引用,并且由GC收集。

因此,在这种情况下,它会将True标记用于Subscribe方法。

正如@Haukinger所说:

在Prism文档中 https://github.com/PrismLibrary/Prism/blob/ef1a2266905a4aa3e7087955e9f7b5a7d71972fb/Documentation/WPF/30-ModularApplicationDevelopment.md#initializing-modules

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.