In the beginning events in C# were awesome. Some of us came from Java, and used to have to implement interfaces named IButtonClickListener on some inner classes whatever nonsense just to react to some button being clicked, but not in C#. No, in C# you just did the following:
public partial class Form1 : Form
{
Button newButton;
public Form1()
{
InitializeComponent();
newButton = new Button()
{
Text = "Click me!",
Left = 20,
Top = 20
};
newButton.Click += new EventHandler(HandleClick);
this.Controls.Add(newButton);
}
private void HandleClick(object sender, EventArgs e)
{
MessageBox.Show("Hi there!");
newButton.Click -= HandleClick;
}
}
No obnoxious interface nonsense! Delegates! The future is now!
But over 10 years later we have gotten spoiled with anonymous delegates and lambdas, and all of a sudden the C# event model does not seem so cool anymore. Because when you hook up an event handler like this:
newButton.Click += (sender, e) => MessageBox.Show("Hi there!");
do you imagine you can remove it like this:
// fugetaboutit!
newButton.Click -= (sender, e) => MessageBox.Show("Hi there!");
No way! You would have to save the handler to a variable to have a reference handy to be able to remove
the handler later:
EventHandler handler = (sender, e) => MessageBox.Show("Hi there!");
Worse! Microsoft added lots of nice generic delegate types Action<T>, Action<T1, T2>, Action<T1, T2, T3> etc that we can't use because we're stuck with the EventHandler delegate types for Events. You would need a wrapper around the Invoke function to make that work.
Would you like to check out what is currently hooked up to your event? Tough!
Clear the whole thing and start over? Get outta here!
But despair no more! I have written a half-assed solution that I think might have been marginally better if it had worked properly!
Presenting: the new and improved Event:
public class Event<TEventArgs,TEventHandler>
where TEventArgs : EventArgs
where TEventHandler : class
{
// the main store for handlers
private Dictionary<int, Action<object, TEventArgs>> handlers =
new Dictionary<int, Action<object, TEventArgs>>();
// a dictionary that maps the original handlers to the generated wrappers
private Dictionary<object, int> operatorAddedHandlers =
new Dictionary<object, int>();
public Event()
{
}
static Event()
{
// check if my TEventHandler type parameter is a delegate type
// where TEventHandler : Delegate is not supported
if (!typeof(TEventHandler).IsSubclassOf(typeof(Delegate)))
{
throw new InvalidOperationException(typeof(TEventHandler).Name + " in generic type parameter TEventHandler is not a delegate type.");
}
}
/// <summary>
/// Maps events of the same name on the container object to the Event field that hides it
/// </summary>
/// <param name="eventGenerator">the object that contains the Event field (typically this)</param>
public void CaptureBaseEvents(object eventGenerator)
{
var fieldNames = new List<String>();
var classType = eventGenerator.GetType();
var fields = classType.GetFields();
// check which field the current instance has been assigned to, store the name
foreach (var field in fields)
{
var val = field.GetValue(eventGenerator);
if (Object.Equals(val, this))
{
fieldNames.Add(field.Name);
}
}
// get a MethodInfo for this class's Invoke method
var invokeHandler =
typeof(Event<TEventArgs, TEventHandler>).GetMethod("Invoke");
// check if any base events exist that have the same name
// if so, hook up our Invoke method
foreach (var fieldName in fieldNames)
{
var classEvent = classType.GetEvent(fieldName);
if (classEvent != null)
{
var tDelegate = classEvent.EventHandlerType;
var d = Delegate.CreateDelegate(tDelegate, this, invokeHandler);
var addHandler = classEvent.GetAddMethod();
Object[] addHandlerArgs = { d };
addHandler.Invoke(eventGenerator, addHandlerArgs);
}
}
}
/// <summary>
/// Invokes the event handlers
/// </summary>
/// <param name="sender">The object that triggered the event</param>
/// <param name="e">The event parameters</param>
public void Invoke(object sender, TEventArgs e)
{
// just in case a handler modifies the handlers
var handlerDelegates = handlers.Select(hs => hs.Value).ToList();
foreach (var handler in handlerDelegates)
{
handler.Invoke(sender, e);
}
}
/// <summary>
/// Removes all handlers
/// </summary>
public void ClearHandlers()
{
handlers.Clear();
}
/// <summary>
/// Gets a list of all handlers and their removal token
/// </summary>
/// <returns></returns>
public IEnumerable<EventHandlerSet<TEventArgs>> GetAllHandlers()
{
// store in list in case someone loops through to find a handler to remove
// that seems kind of likely
var handlerSets = handlers.Select(hs => new EventHandlerSet<TEventArgs>()
{
Handler = hs.Value,
RemovalToken = hs.Key
}).ToList();
return handlerSets;
}
/// <summary>
/// Adds an event handler
/// </summary>
/// <param name="newHandler">The new handler to add</param>
/// <returns>The removal token for the newly added handler</returns>
public int AddHandler(Action<object, TEventArgs> newHandler)
{
// we don't hook up the same handler twice,
// just return its current removal token
if (handlers.Any(ks => ks.Value.Equals(newHandler)))
{
return handlers.Where(ks => ks.Value.Equals(newHandler)).Single().Key;
}
// use a new guid cut off at int32 length for key generator
var newGuid = Guid.NewGuid();
int newKey = BitConverter.ToInt32(newGuid.ToByteArray(), 0);
// it's a lot more likely at 32 bits
while (handlers.ContainsKey(newKey))
{
newGuid = Guid.NewGuid();
newKey = BitConverter.ToInt32(newGuid.ToByteArray(), 0);
}
handlers.Add(newKey, newHandler);
return newKey;
}
/// <summary>
/// Adds a new handler to the Event field
/// </summary>
/// <param name="thisEvent">The event field</param>
/// <param name="newHandler">The handler to add</param>
/// <returns></returns>
public static Event<TEventArgs, TEventHandler> operator +(Event<TEventArgs, TEventHandler> thisEvent, TEventHandler newHandler)
{
var handlerDelegate = newHandler as Delegate;
if (handlerDelegate == null)
throw new InvalidOperationException("Handler is not a delegate type!");
// if this handler has already been added, do nothing
if(thisEvent.operatorAddedHandlers.ContainsKey(newHandler)){
return thisEvent;
}
var removalToken = thisEvent.AddHandler(delegate(object sender, TEventArgs e)
{
handlerDelegate.DynamicInvoke(new object[] { sender, e });
});
thisEvent.operatorAddedHandlers.Add(newHandler, removalToken);
return thisEvent;
}
/// <summary>
/// Removes the specified handler
/// </summary>
/// <param name="handler">The handler to remove</param>
public void RemoveHandler(Action<object, TEventArgs> handler)
{
if (handlers.Any(ks => ks.Value.Equals(handler)))
{
var removalToken = handlers.Where(ks => ks.Value.Equals(handler)).Single().Key;
handlers.Remove(removalToken);
}
}
/// <summary>
/// Removes the specified handler
/// </summary>
/// <param name="removalToken">The handler's removal token</param>
public void RemoveHandler(int removalToken)
{
if (handlers.ContainsKey(removalToken))
handlers.Remove(removalToken);
}
/// <summary>
/// Removes the specified handler
/// </summary>
/// <param name="thisEvent">The event field</param>
/// <param name="handler">The handler to remove</param>
/// <returns></returns>
public static Event<TEventArgs, TEventHandler> operator -(Event<TEventArgs, TEventHandler> thisEvent, TEventHandler handler)
{
if (!thisEvent.operatorAddedHandlers.ContainsKey(handler))
return thisEvent;
var removalToken = thisEvent.operatorAddedHandlers[handler];
thisEvent.RemoveHandler(removalToken);
return thisEvent;
}
}
public class EventHandlerSet<TEventArgs>
{
internal EventHandlerSet() { }
public int RemovalToken { get; set; }
public Action<object, TEventArgs> Handler { get; set; }
}
I've made it so that it's mostly a drop-in replacement for pre-existing events. Obviously you need to inherit from the class implementing the events. So let's take that boring old button we had, and jazz up the click event:
public class NewAndImprovedButton : System.Windows.Forms.Button
{
public NewAndImprovedButton()
: base()
{
Click.CaptureBaseEvents(this);
}
public new Menno.Event.Event<EventArgs, EventHandler> Click = new Menno.Event.Event<EventArgs, EventHandler>();
}
Turns out you can hide an event with a field. Who knew? Also, the CaptureBaseEvents in the constructor only works because fields are initialized before the constructor runs. Otherwise I'd have had to do something odd and confusing. More so.
If we take the first piece of code and replace Button by NewAndImprovedButton, like so:
public partial class Form1 : Form
{
NewAndImprovedButton newButton;
public Form1()
{
InitializeComponent();
newButton = new NewAndImprovedButton()
{
Text = "Click me!",
Left = 20,
Top = 20
};
newButton.Click += new EventHandler(HandleClick);
this.Controls.Add(newButton);
}
private void HandleClick(object sender, EventArgs e)
{
MessageBox.Show("Hi there!");
newButton.Click -= HandleClick;
}
}
Everything keeps working exactly the way it did. I implemented the + and - operators to mirror the current Event syntax, and the CaptureBaseEvents method hooks up the event in the base class that the field hides to the Invoke method. Magic!
But we did not make this to keep working the same way. Here's what's new:
- an AddHandler method that takes an Action<object, TEventArgs> and returns an int that functions as a token.
- (obviously) a RemoveHandler that an int token.
- for good measure: a RemoveHandler that takes an Action<object, TEventArgs>
- a ClearHandlers method
- a GetAllHandlers method that returns all handler delegates and their tokens, even the ones added through reflection.
Of course there are some rough edges too:
- Field cannot be readonly if you use the operators. Anything could happen.
- Operators generate wrappers through reflection. Performance is bound to be questionable.
- Probably hundreds of corner cases I haven't considered.
Still, now you can do this:
int removalToken = 0;
removalToken = newButton.Click.AddHandler((sender, e) =>
{
MessageBox.Show("Hi there!");
newButton.Click.RemoveHandler(removalToken);
});
For some folks, that's worth a few rough edges.