One issue encountered by almost all developers is the ability to fetch data from somewhere, and do it without freezing the UI.  I recently found myself in this scenario while working on a Windows Presentation Foundation (WPF) application.  I looked around at the various ways to handle concurrency in the .NET framework (threads, background worker process, etc).  I found the Task Parallel Library (TPL), which I hadn’t used before.  So did some reading about it on MSDN and realized how easy it was to use compared to the other options.  With the following code I was up and running, calling my method to handle some task I wanted done on a separate thread.

This seemed almost way too simple compared to the other methods.  Could it really be this simple?  Well, there is a little bit more you can add if you want to be nice to your end users and handle exceptions that might occur in the task, but it really was this simple.  Even fetch data wasn’t too much more code then above.

This code creates a task that returns a list of type People.  It then waits for the task to finish, and when it does finish it gets the task’s results, which contains our list of People (I create a new ObservableCollection of People because I’m working WPF, which binds to ObservableCollections).  When bit of logic I added to this is to make sure that the task didn’t finish because of a fault or exception in the task.

Again, how hard was that?  Pretty simple no creating threads or getting threads from pools, it does all that thinking for you.  It’s as if Microsoft has started to listen to developers’ pain points and addressing them.

Like this post? Share it!