Tuesday, September 13, 2016

new callback pattern

I wound up needing to build out my callback pattern a bit before continuing with UI. The simplest approach (have the game code publish delegates), had so many problems at The Old Company that I was afraid to apply it here. Instead I wound up implementing something similiar to a solution I made at TOC: a generic interface-based substitution for the C# delegate type.

Since I didn't have legacy code to support, I went one step further and made my custom delegate type single-shot--that is, after it calls its callbacks, it blanks its own callback list.

This serves both for stop-loss (leaked memory can't last past the next invocation of the delegate), and also creates nice patterns for the common case where you're registering for something that is only going to happen once (or at least once per time you want to register for it). The obvious example is logging in--you want to start the login process and then hear that it's done, and that's it; you don't have to write deregistration code and then reason about it to make sure it will be called.

Of course you need a way to handle events that you want to continuously listen for. My solution for that is to have the callback reregister with MossDelegate in a finally block (MossDelegate already needed to be re-entrant safe anyway). Because registering is O(1) without generating any allocations, this seems like a reasonable tradeoff.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.