订阅的事件在不同的模块中的棱镜

问题描述:

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

+0

你在哪里定义事件?发布者和订阅者都需要引用完全相同的类型。 – Haukinger

+0

事件在'EventModule'中定义,在'LoginModule'中触发,我试图在'EventModule'中订阅它 – keeg

+0

它是否与'订阅'方法中的'真正'标志一起工作? – galakt

当订阅事件时,OP没有保持订阅者参考,因此在某一时刻,类没有任何参考并且由GC收集。

所以在这种情况下,它将与True标志一起使用到Subscribe方法中。

由于@Haukinger权指出:

在棱镜文档 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.

+1

当OP说“把它作为一个答案,我会接受”,他的意思是,把这个评论写成一个适当的答案。这仍然是一个评论。你应该为什么这样工作... –

+0

@CallumLinington你是真的 – galakt

+2

你可能想从棱镜文档中提到这一点'注意:默认情况下模块实例的生存期是短暂的。在加载过程中调用Initialize方法之后,将释放对模块实例的引用。如果您没有为模块实例建立强大的参考链,它将被垃圾收集。如果您订阅的事件持有对您的模块的弱引用,则此行为可能会有问题,因为您的模块在垃圾回收器运行时只是“消失”。可能会认为订阅令牌会使订阅保持活动状态。 – Haukinger