Silverlight - Prism Event Aggregator - 事件订阅与退订

Silverlight - Prism Event Aggregator - 事件订阅与退订,第1张

概述今天发现一个bug: 场景:某个可以反复打开、关闭的view (每次打开生成一个viewmodel), 在viewmodel的constuctor中使用Prism EventAggregator订阅了一系列事件。 Bug: 反复打开、关闭后,即使某个事件在控件本次打开后,只触发了一次,事件处理方法却被调用多次。 原因: 1. 订阅事件时,使用了Strong References (keepSubs

今天发现一个BUG:

场景:某个可以反复打开、关闭的vIEw (每次打开生成一个viewmodel), 在viewmodel的constuctor中使用Prism EventAggregator订阅了一系列事件。

BUG: 反复打开、关闭后,即使某个事件在控件本次打开后,只触发了一次,事件处理方法却被调用多次。

原因:

1. 订阅事件时,使用了Strong References (keepSubscriberReferenceAlive 参数值为true)

2. 关闭VIEw时,没有将之前的事件订阅退订

 

 

by default,CompositePresentationEvent maintains weak reference to subscriber's handling method to avoID memory leaks . This means that reference that it holds will not prevent garbage collector from collecting the subscriber.
For most applications this is what we really want,but if you publish large amouts of events very frequently,it may lead to poor performance. keepSubscriberReferenceAlive is the parameter of Subscribe() mathod that controls which (strong/weak) reference is being held.
If we decIDe to keep subscriber reference alive,we'll have to remember to unsubscribe from an event once we don't need it anymore to avoID memory leaks.

 

h ttp://www.mokosh.co.uk/post/Prism-2-WPF-and-Silverlight-Events.aspx

 

解决:实现Idisposable接口,在dispose方法中退订事件

 

此外,Prism (Feb 2009) 在Silverlight上使用week references时不支持事件过滤为Lambda表达式,可用一个方法代替:

 

public

bool

FundOrderFilter(FundOrder fundOrder)


{


return

fundOrder.CustomerID == _customerID;


}


...





FundAddedEvent fundAddedEvent = eventAggregator.GetEvent<FundAddedEvent>();





subscriptionToken = fundAddedEvent.Subscribe(FundAddedEventHandler,ThreadOption.UIThread,false

,FundOrderFilter);http://msdn.microsoft.com/en-us/library/dd458918.aspx
总结

以上是内存溢出为你收集整理的Silverlight - Prism Event Aggregator - 事件订阅与退订全部内容,希望文章能够帮你解决Silverlight - Prism Event Aggregator - 事件订阅与退订所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1047781.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存