Saturday, July 13, 2013

We've been doing multithreaded and asynchronous UI programming all wrong!

About a year ago, Microsoft released version 4.5 of the .Net Framework to the world. No one really cared much but every programmer out there should. Why? Lurking in the shadows of that release was THE solution to our multithreading woes. If you've ever done multithreaded programming, you know three things:

1) Multithreading is painful.
2) Multithreading is messy.
3) Multithreading is painful.

Multithreading is even harder in a GUI environment because most GUI libraries will crash (and crash the whole application too) if a programmer tries to do operations on the UI from another thread. So, the programmer ends up having to write a ton of plumbing to get back onto the UI thread after completing a multithreaded operation to do UI stuff. In addition, multithreaded programming requires thinking outside of how programs and programmers are really wired to think: That is, we think sequentially.

The solution that needs to be ported to every programming language we care about (including C/C++) is async/await. You don't need to know C# to really understand the importance of having these keywords at our disposal:

Easy Asynchrony with C#: No more callbacks!

Watch the video. Yes, it is painful to watch someone write code. But watch it anyway until you understand what async/await are about (the first 30 minutes should be sufficient). Once you see him switch to async/await and comprehend what's going on, your brain will have a happy moment. Well, my brain did anyway. But don't try to imagine what is going on behind the scenes to transform that code into a multithreading wonder yet, at the same time, have sequential, clean, and readable code because then your brain will just explode. My brain exploded trying to think about the behind-the-scenes stuff. Just accept that these keywords do magical things. The await/async keywords are pretty magical, but you know what? We shouldn't care. What we should care about is when our favorite programming languages are going to get these two keywords. If you think about how these keywords work, it really requires fundamental language changes, not some drop-in library where we're only slightly shielded from the painfulness.

I don't normally get excited about programming language keywords. But I've been doing multithreaded programming for a long time and know how hard it is for a lot of programmers to grasp even the basics because it requires a fundamental change to their thinking. The async/await keywords wrap up multithreading in a nice, neat package with a bow on it. Huge game changer. Every programming language that supports multithreading and I/O completion objects need to stop messing around with synchronization objects and adopt these keywords now.

No comments:

Post a Comment