Fully Responsive Theme
Resize your Browser to see the Effect
Parallax Effect
Scroll and Notice the Header Image

Async in C#6

Async in C#6 – Simple example

When you have a large amount of data to be loaded, you won’t be able interact with the window – even to move it around – until the loading is complete. Unless the loading task is done asynchronously. Doing this used to require hundreds of lines describing state machines and so on – Jon Skeet gives a good account of this in his Pluralsight course on Async.

I like his example of the pizza delivery as the means of explaining asynchrony – you order your meal over the phone but don’t hang about at the front door waiting, you go get the dishes ready. Here, we order our data and setup our display whilst it arrives.

Below, is the results of a couple of hours scrapping with syntax to achieve the same result in a toy WPF app. Here, I’ve got a 120 superheroes, belonging to classes who are assigned random grades for several subjects. The notion came from an early morning drill where I was exploring how quickly could I throw a small object hierarchy together from an external source.

The original code is here though likely to be added to as I use other drills on it. Note the use of $ string interpolation rather than string.format – a nice new feature.

A non lambda version, requiring the use of the Async/Await in the main method body itself. And an alternative that hides this requirement completely inside a lambda of it’s very own. Basically you can declare a lambda to be async using the following syntax: async()=> await SomeTask()

 /// <summary>
    /// Non lambda version, the methods have to be async
    /// </summary>
    async void getHereosTask2()
        {
        Wilma.Text = await getHeroes2();
        }


    async Task<string> getHeroes2()
        {
        return await Task.Run(() =>
        {
            StringBuilder sb = new StringBuilder();
            foreach (StudentClass c in School.SuperHeroSchool)
                {
                sb.Append($"Class Name: {c.Name} \nDate:{DateTime.Today.ToShortDateString()}\n");
                foreach (Student student in c.Students)
                    {
                     sb.Append($"\n*** {student.Name}***\n");
                    foreach (var grade in student.Grades)
                        {
                        sb.Append($"{grade.Key} : {grade.Value} \n");
                        }
                    }
                }
            return sb.ToString();
        });
        }

Lambda style:

 /// <summary>
    /// Async style one: here we hide the need for the async inside lambdas :)
    /// Notice how the second method, Task<string> is NOT async.  Instead we just make a nice async lambda lambada!
    /// </summary>
      void getHereosTask()
        {
          Task<string> sb = Task.Run(async() => await getHeroes());
          Wilma.Text = sb.Result;
        }

       Task<string> getHeroes()
        {
        return Task.Run(() =>
        {
            StringBuilder sb = new StringBuilder();
            foreach (StudentClass c in School.SuperHeroSchool)
                {
                sb.Append($"Class Name: {c.Name} \nDate:{DateTime.Today.ToShortDateString()}\n");
                foreach (Student student in c.Students)
                    {
                    sb.Append($"\n*** {student.Name}***\n");
                    foreach (var grade in student.Grades)
                        {
                        sb.Append($"{grade.Key} : {grade.Value} \n");
                        }
                    }
                }
            return sb.ToString();
        });
        }

Final note: at a later stage, an F# version will be done just to practice crossing the idioms over! 🙂