TrueWill provides an example of a good implementation of an event and a method for raising it. This is a Microsoft Click class event. First of all, note that they use an EventHandlerList to store tasks in ...
protected EventHandlerList Events { get { if (events == null) { events = new EventHandlerList(this); } return events; } } ... public event EventHandler Click { add { Events.AddHandler(EventClick, value); } remove { Events.RemoveHandler(EventClick, value); } }
Now pay attention to the real OnClick promotion OnClick , it is probably very different from what you used to see ...
protected virtual void OnClick(EventArgs e) { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventClick]; if (handler != null) handler(this, e); }
... don't worry about the line Contract.Requires(e != null); that their contract management infrastructure, but notice that it pulls it from EventHandlerList , and then if this handler is not null , they will start it.
Another thing that is probably worth noting here is that you probably won't need to implement your events in exactly the same way, but the programming guide released by Microsoft actually raises the race condition in the second part of this guide that TrueWill indicates. You can find this guide here . This is actually one very good guide from Microsoft.
Now to your point , I believe that events should be tested, and here is the mechanism that I used in the past ...
private ManualResetEvent _eventRaised = new ManualResetEvent(false); [TestMethod] public void TestSomething() { _eventRaised.Reset();
source share