Monday, March 26, 2012

In this blog I will continue with the async example I wrote in a previous blog post. I showed the new async library of dot.net 4.5. Which will also work with Mono. All the samples I show in this blog post will also work on the latest Mono. These methods can be handy to download from multiple sources like twitter and facebook. Sometimes we want to get all the messages from all sources. Sometimes we only the messages from the fastest (the first returning) source and sometimes we want all the messages that returned within a certain timespan. This where the new Async library with the WhenAll, WhenAny methods come in very handy.

As we can see it will get all the sources. This will take approximatly 5 seconds because of the sleep of 5 seconds in the GetSleep.
If we only want the first (and fastest) result whe can use the Task.WhenAny method:

This works fine, but sometimes we want the most results within a certain timespan. Like in a realtime mashup situation. To accomplish this we will need a timeout. We will let this take 2 seconds and after this it has to return data and skip the ones that are not finished yet. For example we want to query several search engines and merge the results. I have some other sources here, because most of the sources need application keys to query, which is a bit out of scope for this blog post. For this sample we take the above code and change it so that it will timeout after 2 seconds. The result is: