Wednesday, January 17, 2007

Why you should be using the .NET Framework

Larry Osterman has written a series of posts about software contracts. Well that's what they are meant to be about, but in the end they've been more about the fact that using the PlaySound API asynchronously is really amazingly difficult. One problem is that it's not documented particularly well, but the main problem is the design. The caller allocates some memory, which it must clean up after the sound has finished playing, but if you play it asynchronously you don't get any notification of when it has finished. There's a number of solutions, like kicking off the call synchronously in a separate thread or polling to see when the sound has finished. Larry even went so far as to provide some code to find out how long a WAV file is. Unfortunately some developers 'solve' the problem by just never freeing the memory.

Anyway, this just reminded me of what a complete PITA the Windows API can be, with weird structures and pointers to pointers, and all the docs expecting you to be a C programmer. To be fair, lots of it was designed 15 or more years ago, when PCs were completely different beasts to what they are now but I'm so glad most of my development is now using the .NET Framework. And playing a sound? Actually that was a gaping hole in .NET 1.1 but .NET 2 has the SoundPlayer class. For an async experience, call AsyncLoad, respond to the LoadCompleted event and then call Play and that's it.   

No comments: