I have been doing lots of code using callbacks recently and it happen to be in .Net (C#). I need some time to get used to the term, conventions and helpers that is available in .Net but in the end it is actually quite convenient with lots of predefined construct available.
Here's to sum things a little :
- For "raw" callback there's delegate. It's only a little higher than C's function pointer i.e: provide type checking.
- Above it there's event construct. It restricts delegate so the client can only add and remove itself to it but not others. Having that restriction it can now be viewed as broadcaster-subscriber model implementation (or signal-slot in qt term).
- Now, it gets more interesting : there are predefined Event Handling Framework that can be used so I can save some typing and maintenance. For typical purpose, you could use default non-generic version. What you need to do is declare the Event on the broadcaster :
public event EventHandler SomethingHappen;
and on the client, make the handling function based on the predefined argument pattern,
private void OnPlayFinished(Object sender, EventArgs e) { ... do work... }
and subscribe it somewhere :
broadcasterObject.SomethingHappen += OnPlayFinished;
This is what being used throughout WindowsForms-related code in VisualStudio that we could use for our own purpose too.
No comments:
Post a Comment