C#的事件挂载语法是:
source.SomeEvent += new SomeEventHandler(MyEventHandler)
这在事件源上创建了一个监听器的强引用,使得事件监听器的生命周期收到事件源的限制,会造成内存泄露问题。
控件的作者应该避免给使用者引入内存泄漏问题,控件应该采用Weak Event模式。
实现Weak Event模式
Before .Net 4.5 the .Net framework came with a class and an interface that allowed implementation of the weak event pattern:
- WeakEventManager which is where all the pattern plumbing is encapsulated
-
IWeakEventListener which is the pipe that allows a component to connect to the WeakEventManager
plumbing
(Both are located in the WindowsBase assembly that you’ll need to reference yourself if you’re not developing a WPF project which should already correctly reference it.)
First the custom weak event manager:
public class EventManager : WeakEventManager
{
private static EventManager CurrentManager
{
get
{
EventManager manager = (EventManager)GetCurrentManager(typeof(EventManager));
if (manager == null)
{
manager = new EventManager();
SetCurrentManager(typeof(EventManager), manager);
}
return manager;
}
}
public static void AddListener(EventSource source, IWeakEventListener listener)
{
CurrentManager.ProtectedAddListener(source, listener);
}
public static void RemoveListener(EventSource source, IWeakEventListener listener)
{
CurrentManager.ProtectedRemoveListener(source, listener);
}
protected override void StartListening(object source)
{
((EventSource)source).Event += DeliverEvent;
}
protected override void StopListening(object source)
{
((EventSource)source).Event -= DeliverEvent;
}
}
Then our event listener:
public class LegacyWeakEventListener : IWeakEventListener
{
private void OnEvent(object source, EventArgs args)
{
Console.WriteLine("LegacyWeakEventListener received event.");
}
public LegacyWeakEventListener(EventSource source)
{
EventManager.AddListener(source, this);
}
public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
OnEvent(sender, e);
return true;
}
~LegacyWeakEventListener()
{
Console.WriteLine("LegacyWeakEventListener finalized.");
}
}
.Net 4.5 has introduced a new generic version of the legacy WeakEventManager: class MSDN documentation" href="http://msdn.microsoft.com/en-us/library/hh199438(v=vs.110).aspx" style="margin: 0px; padding: 0px; border: 0px; text-decoration: none; color: rgb(128, 0, 128);">WeakEventManager<TEventSource, TEventArgs>.
(This class is located in the WindowsBase assembly too.)
public class WeakEventListener
{
private void OnEvent(object source, EventArgs args)
{
Console.WriteLine("WeakEventListener received event.");
}
public WeakEventListener(EventSource source)
{
WeakEventManager<EventSource, EventArgs>.AddHandler(source, "Event", OnEvent);
}
~WeakEventListener()
{
Console.WriteLine("WeakEventListener finalized.");
}
}
There is only a single line of code to write, really clean.
对于客户端透明的实现方式
上述两种方式都需要客户端在订阅事件的时候修改原有的代码。
参考资料[3] 提供了对于客户端透明的实现方式,但其中使用的DynamicInvoke会造成性能问题。参考资料[4]是更可行、实际可用的方式。
作者Thomas Levesque在MAY 6, 2016 AT 20:06说,相比于.Net 4.5提供的WeakEventManager,他的方案更加方便实用:
Well, IMO WeakEventManager isn’t very natural to use; there’s a lot of boilerplate code to write, and it doesn’t look anything like a normal event. Other than that, I don’t think there are fundamental differences between the two.
参考
[1] The .NET weak event pattern in C#
[2] [C#] A SIMPLE IMPLEMENTATION OF THE WEAKEVENT PATTERN, 2010.
[3] thomaslevesque/WeakEvent
[4] WEAK EVENTS IN C#, TAKE TWO, 2015.08。