2016-06-21 54 views
1

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

回答

1

當訂閱事件時,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