-
Notifications
You must be signed in to change notification settings - Fork 16
WeakEvent
ikopylov edited this page Dec 26, 2014
·
2 revisions
Incorrect usage of .NET events are often lead to memory leaks. You should always remove subscription when you destroy listener. But in some cases there's no any good point to do so. For that cases you could use our MulticastWeakDelegate. It stores a weak reference to listener which not stop the GC from collection the listener object.
Usage sample:
public class SampleClass
{
// create our weak delegate for Start notifications
private MulticastWeakDelegate<EventHandler> _starting = new MulticastWeakDelegate<EventHandler>();
// Wrap our weak delegate with standard event
public event EventHandler Starting
{
add { _starting.Add(value); }
remove { _starting.Remove(value); }
}
public void Start()
{
// Get delegate to notify all alive listeners
var deleg = _starting.GetDelegate();
if (deleg != null)
deleg(this, EventArgs.Empty);
}
}