-
One of the new features with the .Net framework 4.5 that looks particularly useful are the new asynchronous features.
This promises to make asynchronous programming far easier. (At least for relatively simple tasks)
Let’s try it out and see.
We’ll need some relatively intensive/slow function to test it with. I’m going to try calculate PI (badly)
Start with a new console project
Add a new class called PiCalculator
We will then add a normal function (not asynchronous) for calculating pi.
This is one I cobbled together from other parts of the internet.
It takes one parameter that determines how many iterative steps it goes through. The more steps the more accurate the result will be.
We can call this method and output easily enough.
This will give us the following output
Beginning
3.1415928535897532384686437064
End.
It took about 5 seconds to run.
Now to introduce the async keywords.
First well need to make and async friendly version of our calculate method.
Our async friendly version needs to return a task object.
Now we can create a method with our new async keyword that will use this functionPutting it all together gives us this.
Since the Calculation is running asynchronously. The output from calling the Go method is now
Begining
End
3.1415928535897532384686437064
The main thread continues on while our new asynchronous method works away in the background.
There’s a lot more to asynchronous methods than this.
There is more information to be found at.
http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
and
http://msdn.microsoft.com/en-us/magazine/jj991977.aspx
- Back to Blogs
Dataworks Blog