• Asynchronous Programming in C# 5

    by  • March 21, 2012 • .Net, Programming • 0 Comments

    With each new version of C# we see some great new additions. In version 2 we saw the introduction of generics, and in 3 we saw LINQ.

    In version 5 we are seeing some new features to handle the rise of SaaS (Software as a service), the forefront of this is asynchronous programming. An overview of this is available as a downloadable whitepaper.

    I’ll be talking about the awesome Roslyn Project in another blog post soon.

    Channel 9 has a collection of great introduction videos on the new keywords associated with Async.

    In the above video, Stephen Toub goes deep into the design and architecture of the new Async features in C# and VB.NET (yuck), which rely heavily on .NET’s Task Parallel Library.

    But of course the man to best explain Async is Anders Hejlsberg, the original implementor of C# and a man I was luckily enough to meet while working at Microsoft. – He’s crazily smart!

    To find out more about C# 5, you can visit the MSDN website. You can even try it out now by downloading the Visual Studio 2011 Beta.

    The new await and async keywords are an interesting beast. It can be used to turn a conventional method into an async method, with the clever stuff done behind the scenes by the compiler. Have a look at the following code.

    private async void WaitAround()
    {
        string url = "http://www.MrPfister.com";
        string content = await new WebClient().DownloadStringTaskAsync(url);
        this.textBox1.Text = string.Format("Page {0} supports XHTML 1.0: {1}",
          url, content.Contains("XHTML 1.0"));
    }
    

    The await word blocks execution of the code, and returns control to the dispatch queue until the method can continue. By using await, the thread itself doesn’t block and thus means that this allows more code to be pushed onto the UI thread -not the best idea but allows simpler programming for small programs.

    About

    Software engineer. Tea drinker

    http://MrPfister.com

    Leave a Reply

    Your email address will not be published. Required fields are marked *