WinRT vs. Silverlight - Part 6 - Using Tasks

by Morten 5. October 2011 09:54

See intro blogpost here.

When you start working with WinRT, you start seeing classes missing or changed. A lot of methods are now only asynchronous, like making a web request, opening, reading and writing files etc. They all now on the Task framework, and they do this to ensure you application is always responsive. However without this framework, it would be a pain to code against an API that’s inherently asynchronous all the way through. But with it, it makes it really easy to write code against it.

As an example here’s how you normally write async operations in WPF and Silverlight:

var myObject = new MyClass();
myObject.Completed += (sender,e) => { 
   //Completed event handler 
if(e.Error == null) { statusText.Text = "My Operation has completed: " + e.Result;
} }; myObject.StartAsync(); //Starts process and fires "Completed" event when done

So we first hook up to the event handler, then call start. When you look at the code, the lines are not executed in the order they are written. The completed delegate executes after the operation completes after Start() has been run (even explaining it makes it sound confusing). Also you cannot throw exceptions from an asynchronous running process, because there will be no way to catch it, so you’ll have to parse an exception object back as part of your result and check it.

This pattern makes it hard to read and understand the code, since it’s not immediately obvious what code runs when. Especially when the code gets more complex and/or your eventhandlers are declared elsewhere. When we then nest events, it gets very convoluted quickly:

var myObject = new MyClass();
myObject.Completed += (sender,e) => { 
   if(e.Error == null) {
       //Perform next operation
       var myObject2 = new MyClass();
       myObject2.Completed += (sender2,e2) => { 
           if(e2.Error == null) {
              //Completed event handler
              statusText.Text = "My Operation has completed: " + e2.Result;
} }; myObject2.StartAsync(); } }; myObject.StartAsync();

With the Task framework this becomes very simple and straightforward to write and more importantly read:

var myObject = new MyClass();
try {
     string result = await myObject.StartAsync();
     var myObject2 = new MyClass();
     string result2 = await myObject2.StartAsync();
     statusText.Text = "My Operation has completed: " + result2;
} catch { }

Notice that we don’t bother with checking an error object. We simply use try/catch instead, and the task returns the result up front. If it wasn’t for the little “await” keyword, it looks like this is just good ol’ synchronous programming! This is pure awesomeness!

If you are planning on porting a large application from Silverlight or WPF and it uses a lot of event-based asynchronous programming, you are probably in for some work. Not to say that your application can’t use events, but a lot of the WinRT API’s don’t have eventhandlers any more, so if you insist on keeping it this way, you would have to wrap all the built in tasks into some event-based classes. I would probably rather focus on moving forward and getting this cleaned up. And since the Task framework is already available in .NET 4 and there’s a CTP for Silverlight (and included in upcoming v5!) and WinPhone, you could port your original code to start taking advantage of this, making your code reuse easier and cleaner moving forward.

So how would you go about wrapping an event-based class into a task based method? Well let’s continue using the MyClass example above, and wrap it in a task. Here’s how that would look:

public Task<string> StartAsync()
{
    var tcs = new TaskCompletionSource<string>();
    var obj = new MyClass();
    obj.Completed += (sender,e) => {
        if (e.Error != null)
              tcs.TrySetException(e.Error);
        else
              tcs.TrySetResult(e.Result);
    };
    obj.StartAsync();
    return tcs.Task;
}

Basically we return Task of string, instead of just a string. We use the TaskCompletionSource of string to handle error and result messaging back to the task.

So when should you make a method an asynchronous task? The rule of thumb is: If it takes more than 50ms to execute, it should be asynchronous! This helps a lot towards preventing the UI from becoming choppy and/or unresponsive.

Tags:

Silverlight | Windows Runtime | WPF

Comments (5) -

10/7/2011 8:11:31 AM

Shawn

Morten,

Are you suggesting that a new version of the WPF/Silverlight/Phone SDK will be available some time soon to support this? That would be sweet if I'm understanding this correctly.

Shawn United States

10/7/2011 8:17:56 AM

Morten

Shawn: not suggesting anything. Just showing an interest...
But are you referring to WinRT or just the async framework? The latter you can already do today.
Regarding WinRT it would require more or less a total rewrite of our API and we are not in a position to announce anything just yet (after all this is VERY new and fresh off the counter - aka very buggy and incomplete)

Morten United States

10/7/2011 8:27:59 AM

Shawn

Morten, I was asking if a new version of the SDK's will be out that will have the async framework "baked in".

Shawn United States

10/7/2011 10:23:03 AM

Morten

When the async framework releases as final for all 3 platforms we will probably consider it. Until then you will just have to wrap it like I explained in the last example above.

Morten United States

10/7/2011 12:16:06 PM

Shawn

Cool, thanks!

Shawn United States

3/28/2012 6:13:53 PM

five finger shoes vibram

YC- Any training Vibram shoes gets stale after four to six weeks and michael kors watch stops working http://www.vibramfive-sales.com/. So whether you're looking to Vibram Bikila learn how to use kettle vibrams five fingers bells for the first time or if you're a seasoned vet and looking for a new michael kors mid-size mercer chronograph watch, golden challenge, kettle bell books, DVD's and five finger vibram bikila instructional courses are always a good bet. No amount of vibram fivefinger shoes for women instructional articles, videos, books, or DVD's can replace in-person instruction michael kors sale when it comes to kettle bell five fingers uk sale training. Look up your local RKC and purchase some vibram five fingers kso training sessions as a gift to get your kettle bell aficionado going on the right foot - or watches michael kors to perfect their technique. These vibram 5 fingers sale may look a little different and special but actually they are really quite cool and can be used for a five fingers shoes uk shop multitude of purposes http://www.michael-kors-sale.net/. Whether you just want something to walk around the home or to the speed shoes, perhaps you climb or do some light trekking or you may want the Vibram Five Fingers for running. There is vibram five finger toes very little padding on the shoes, as Vibram have designed them in a way that reflects the michael kors mens watches natural properties of feet; this means five fingers uk sale that there is very little interference from the shoes, which effectively mimic barefoot movement. http://www.vibram-five-finger.net/

five finger shoes vibram People's Republic of China

3/31/2012 7:44:55 PM

annora coast dress

LF- Barbour jackets are a clothing manufacturer originating from the north of coast clothing England; they have gained a solid http://www.uk-barbour-jacket.org/ reputation in the creation and manufacturing of barbour jacket women hardwearing, durable and fashionable coast irah red designed for outdoor use. The reason that they are so popular at present is largely due to the recent country/townie barbour quilted jacket fashions that are set to be big coast fashion news this season. As a hunting-type barbour quilted jacket ladies, the Barbour quilted jacket is perfect for adapting to recent coast victory dress styles. Founded in 1894, the company red barbour jacket has never been far from the minds of floral dresses fashion conscious individuals throughout the world. Often considered the sophisticated man's style of fashion, these coats form part of a classical style of womens barbour jackets dress. Renowned for their coast maxi dresses hardwearing, high-quality garments, Barbour really are head and shoulders above the rest. They are famous for providing clothing for many barbour shop of the country's high-flying elite; as such, they have a fantastic reputation, which is coast evening dresses uk much warranted. http://www.uk-womendresses.biz/

annora coast dress People's Republic of China

Pingbacks and trackbacks (3)+

Comments are closed

About the author

Morten Nielsen

Silverlight MVP

Morten Nielsen
<--That's me
E-mail me Send mail

Twitter @dotMorten 

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2005-2011

Month List

RecentComments

Comment RSS