是否可以使用WeakEventManager在静态事件上创建弱事件侦听器?
我想在静态CompositionTarget.Rendering事件上创建一个弱事件监听器,以避免在我不知道WPF / Silverlight源元素的生命周期时发生内存泄漏.
我在weak event pattern之前实现了渲染事件管理器:
public class RenderingEventManager : WeakEventManager { public static void AddListener(IWeakEventListener listener) { CurrentManager.ProtectedAddListener(null,listener); } public static void RemoveListener(IWeakEventListener listener) { CurrentManager.ProtectedRemoveListener(null,listener); } private static RenderingEventManager CurrentManager { get { var managerType = typeof(RenderingEventManager); var manager = (RenderingEventManager)GetCurrentManager(managerType); if (manager == null) { manager = new RenderingEventManager(); SetCurrentManager(managerType,manager); } return manager; } } protected sealed override void StartListening(object source) { CompositionTarget.Rendering += this.OnCompositionTargetRendering; } protected sealed override void StopListening(object source) { CompositionTarget.Rendering -= this.OnCompositionTargetRendering; } void OnCompositionTargetRendering(object sender,EventArgs e) { this.DeliverEvent(sender,e); } }
并在一个简单的窗口中测试了经理:
public partial class Window1 : Window,IWeakEventListener { public Window1() { InitializeComponent(); RenderingEventManager.AddListener(this); } bool IWeakEventListener.ReceiveWeakEvent(Type managerType,object sender,EventArgs e) { return true; } }
未调用ReceiveWeakEvent方法.调用OnCompositionTargetRendering,但似乎DeliverEvent不能像我预期的那样工作.
将侦听器添加到Button.Click等实例事件中工作正常…
测试项目在.NET 4.0 Client Profile上.
A post on Microsoft Connect from 2009声明不支持静态事件,
但我检查了WeakEventManager源代码,它看起来没问题:
protected void ProtectedAddListener(object source,IWeakEventListener listener) { Debug.Assert(listener != null,"Listener cannot be null"); object sourceKey = (source != null) ? source : StaticSource; ... }
解决方法
自己弄清楚:将DeliverEvent方法的sender参数更改为null:
void OnCompositionTargetRendering(object sender,EventArgs e) { this.DeliverEvent(null,e); }