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
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 function
Putting it all together gives us this.
Since the Calculation is running asynchronously. The output from calling the Go method is now
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.
- Back to Blogs