Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Visual Studio Async CTP for the rest of us…

, 22 Nov 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Visual Studio Async CTP for the rest of us…

Today at PDC 2010, they announced Asynchronous functions in C# and VB.NET. So what exactly does that mean? I'll give you the definition first:

Asynchronous operations are methods and other function members that may have most of their execution take place after they return. In .NET, the recommended pattern for asynchronous operations is for them to return a task which represents the ongoing operation and allows waiting for its eventual outcome.

You completely understand right? Me neither! I have been reading about it and I wanted to share my understanding of it.

Imagine an application (like the Netflix example) with a lot of data. You would experience the following behavior using a synchronous application.

  • The program becomes non-responsive.
  • You cannot move, resize the window while data is loading.
  • You cannot hit the Close button to end the program while data is loading.

We can definitely do better with asynchronous application with the new tools Microsoft provided for us.

Let’s get started by installing the Visual Studio Async CTP. I will show you how to install it, walking you through the example application and then Tips/Tricks that will save you some time when getting started.

You can download the Visual Studio Async CTP here. The C# Language Specification for Asynchronous Functions is included in the CTP or you can download it individually as well. After you have it downloaded, then double click the setup file and finish installing it. After you have installed it, it will ask for a reboot. Go ahead and reboot after its finished.

SNAGHTMLae51a5c

SNAGHTMLae6b237

SNAGHTMLaf4418b

After it is finished installing, you will see the following screen below which contains all kinds of goodies.

SNAGHTMLaf5220a

What we are going to do is play with the example project and convert it from a synchronous application to an asynchronous Silverlight application. So click the “Find Movies” button to load the VS2010 project that we are going to work with. After VS2010 is loaded, then click the “Walkthrough” link for a document Microsoft prepared to walk you through it. I am going to use the document as my guide for this tutorial.

image

After you have loaded the project and hit Build, then it will generate an error on the line below. 

image

Let’s fix the reference now. We want to add AsyncCtpLibrary_Silverlight.dll to this project. This file should be located in your “My Documents\Microsoft Visual Studio Async CTP\Samples” as shown below:

SNAGHTMLb05badf

After it’s added, you should see it in your references:

image

Now we are going to play with two new keywords, await and async (defined by Microsoft below).

Await expressions are used to suspend the execution of an asynchronous functions until the awaited task completes.

Inside asynchronous functions await expressions can await ongoing tasks, which causes the rest of the execution of the asynchronous function to be transparently signed up as a continuation of the awaited task.

In the sample project, you are only going to change two methods, LoadMovies() and QueryMovies(). You are going to refactor these methods to LoadMoviesAsync() and QueryMoviesAsync() and prefix them with the async contextual keyword. We will use await when calling our data as shown below:

async void LoadMoviesAsync(int year)
{
    resultsPanel.Children.Clear();
    statusText.Content = "";
    var pageSize = 10;
    var imageCount = 0;
    while (true)
    {
        statusText.Content = string.Format("Searching...  {0} Titles", imageCount);
        var movies = await QueryMoviesAsync(year, imageCount, pageSize);
        if (movies.Length == 0) break;
        DisplayMovies(movies);
        imageCount += movies.Length;
    }
    statusText.Content = string.Format("{0} Titles", imageCount);
}

async Task<Movie[]> QueryMoviesAsync(int year, int first, int count)
{
    var client = new WebClient();
    var url = String.Format(query, year, first, count);

    // The following line doesn't compile. To learn how to fix it,
    // follow the walkthrough: http://go.microsoft.com/fwlink/?LinkId=203988
    string data = await client.DownloadStringTaskAsync(new Uri(url));
    
    var movies =
        from entry in XDocument.Parse(data).Descendants(xa + "entry")
        let properties = entry.Element(xm + "properties")
        select new Movie
        {
            Title = (string)entry.Element(xa + "title"),
            Url = (string)properties.Element(xd + "Url"),
            BoxArtUrl = (string)properties.Element
		(xd + "BoxArt").Element(xd + "LargeUrl")
        };
    return movies.ToArray();
}

If you have problems following my example, then check out Page 4 of the AsyncGettingStartedWalkthrough.docx that I provided a link to earlier.

At this point, if you run the application again, give it a current year (like 2007), you will notice that the program is still responsive. This is exactly why we would want to use this.

SNAGHTML1a4afe6

Some Tips/Tricks that I discovered while working with the Async CTP.

  1. Notice the red font on async and await below? They have not been added to Visual Studio Intellisense but the program will still compile.

    image

  2. If you lose the start page for the CTP, its can be found at: “C:\Users\User ID\Documents\Microsoft Visual Studio Async CTP\Documentation”. You can also find all of the other documentation instead of downloading each piece separately.

    SNAGHTML53b2bc

  3. If building for Silverlight, then make sure you have the Silverlight 4 SDK and Silverlight 4 Tools for VS2010.
  4. The .dlls required to use this is located in your C:\Users\User ID\Documents\Microsoft Visual Studio Async CTP\Samples.

    SNAGHTML579b46

That is everything that I wanted to show everyone. Hopefully this clears up some of the confusion and you will understand it a little better. Thanks for reading.

----------------------------------------------------------------------------------------------------------------------------------

Note: I have included a demo of the project as well as the source code for those that need it.

----------------------------------------------------------------------------------------------------------------------------------

alt Subscribe to my feed

<iframe marginwidth="0" marginheight="0" src=""http://ads.geekswithblogs.net/a.aspx?ZoneID=5&Task=Get&PageID=31016&SiteID=1"" frameborder="0" width="1" scrolling="no" height="1" />

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

mbcrump
Software Developer (Senior) Telerik
United States United States
Michael Crump is a Silverlight MVP and MCPD that has been involved with computers in one way or another for as long as he can remember, but started professionally in 2002. After spending years working as a systems administrator/tech support analyst, Michael branched out and started developing internal utilities that automated repetitive tasks and freed up full-time employees. From there, he was offered a job working at McKesson corporation and has been working with some form of .NET and VB/C# since 2003.
 
He has worked at Fortune 500 companies where he gained experience in embedded systems design and software development to systems administration and database programming, and everything in between.
 
His primary focus right now is developing healthcare software solutions using Microsoft .NET technologies. He prefers building infrastructure components, reusable shared libraries and helping companies define, develop and automate process standards and guidelines.
 
You can read his blog at: MichaelCrump.net or follow him on Twitter at @mbcrump.
Follow on   Twitter

Comments and Discussions

 
QuestionThere are no pictures. Please fix. Pinmemberpiotr_fe18-Jul-13 11:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150326.1 | Last Updated 22 Nov 2010
Article Copyright 2010 by mbcrump
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid