public void TestWeakEvent_Extension() { EventRaisingClass observed = new EventRaisingClass(); _eventRaised = false; var handler = new EventHandler <EventArgs>(GetCallback()).MakeWeak(h => observed.Event -= h); observed.Event += handler; Assert.AreEqual(1, observed.SubscriptionCount); // pull the WeakEventHandler instance out of the callback var weakEventHandler = handler.Target as WeakEventHandler <EventArgs>; Assert.IsNotNull(weakEventHandler); // when target goes out of scope, event is not detached. the observer will be // temporarily leaked until the event fires InvalidateEventHandler(weakEventHandler); Assert.AreEqual(1, observed.SubscriptionCount); // if the target is no longer alive when the event is raised, the event handler should be // automatically unregistered, which will cause the observer to unsubscribe from the source observed.RaiseEvent(EventArgs.Empty); Assert.AreEqual(0, observed.SubscriptionCount); Assert.IsFalse(_eventRaised); }
public void TestSubscription_Simple() { // subscription should not occur until handler is registered EventRaisingClass observed = new EventRaisingClass(); Assert.AreEqual(0, observed.SubscriptionCount); _eventRaised = false; observed.Event += new WeakEventHandler <EventArgs>(GetCallback()).Handler; // subscription should have occurred Assert.AreEqual(1, observed.SubscriptionCount); observed.RaiseEvent(EventArgs.Empty); Assert.IsTrue(_eventRaised); }