Polling vs. Event Driven Models
I’ve been spending the last little bit of my weekend creating a utility class or two that will give me event driven mouse and keyboard events, as opposed to the default polling mechanism in XNA. I thought it would be worth taking a little time to outline what these two models are, what their advantages and disadvantages are, and how to make event driven events in XNA.
To start, in XNA, the default is polling. At any point in time, you can say, “Give me the current status of device X.” Fortunately, in XNA, this comes back to you in the form of an actual struct, organized in an intelligent way. You don’t need to, say, poll the serial port or anything ridiculous like that.
To know if a button was pushed, you need to save the state from the last update and compare the two. Last time it was up, this time it’s down, so I know the button was pushed.
On the other hand, if you’ve ever done any programming for Windows Forms or WPF, you’re more accustomed to a different model that is event driven. You don’t poll the mouse for it’s state. Instead, you attach methods to events that are triggered whenever certain criteria are met. Like a mouse click, a mouse double click, a mouse move, etc. Your code includes one line to attach (or another to detach) a method from the event. The rest of your work is done writing the body of that method to explain what your program should do when that event happens.
While polling gives you a little more power, in the sense that you’re not restricted to whatever system is managing the events can do, it’s also a lot more work. Because you’re thinking in events. You’re thinking, if the player pushes the A button, I want this to happen. So you go write the code for polling to check if the button has just been pressed, and then in your if statement, you throw in the code to handle this.
So for the sake of making your code match your mental model, it makes sense to turn your polling code into event driven code.
And actually that last sentence of two paragraphs ago, about throwing your code into the if statement is significant too. I’ve seen a lot of people’s XNA code over the years. Including a ton of my own. Most people, including me, have a natural tendency to have all of these polling-based event checks in their
Update method, with the code sitting there inside of the if statement. It grows and grows until it becomes unmanageable. Yes, you can refactor and make it more manageable, but the tendency is to make something that is less readable and maintainable.
With event driven input, you’re attaching methods as event handlers to the events. The natural tendency is to separate things. It’s for this reason that I think event driven input is a better choice overall. Coming soon, I’ll share with you a brief snippet of my code that shows how to set up event driven events instead of polling.