2 chap04
Jason Zhu edited this page 2021-11-21 00:44:27 +11:00

Chapter 4. Essential Language Features

4.1 Preparing the Example Project

4.1.1 Adding the System.Net.Http Assembly

4.2 Using Automatically Implemented Properties

Reference: 5.1.1 Using Automatically Implemented Properties

4.3 Using Object and Collection Initializers

Reference: 5.1.2 Using Object and Collection Initializers

4.4 Using Extension Methods

Reference: 5.1.3 Extension Methods

4.4.1 Applying Extension Methods to an Interface

Reference: 5.1.4 Applying Extension Methods to an Interface

4.4.2 Creating Filtering Extension Methods

Reference: 5.1.5 Creating Filtering Extension Methods

4.5 Using Lambda Expressions

Reference: 5.1.6 Using Lambda Expressions

4.6 Using Automatic Type Inference

Reference: 5.1.7 Using Automatic Type Inference

4.7 Using Anonymous Types

Reference: 5.1.8 Using Anonymous Types

4.8 Performing Language Integrated Queries

Reference: 5.1.9 Performing Language Integrated Queries

4.8.1 Understanding Deferred LINQ Queries

4.9 Using Async Methods

Asynchronous methods: go off and do work in background and notify you when it's completed.

Traditional async methods in C# and .NET (Before .NET Framework) as shown below

Listing 4-32. A Simple Asynchronous Method in MyAsyncMethods.cs File

using System.Net.Http;
using System.Threading.Tasks;

namespace LanguageFeatures.Models {
    public class MyAsyncMethods {
        public static Task<long?> GetPageLength() {
            HttpClient clint = new HttpClient();

            var httpTask = client.GetAsync("http://apress.com");

            // we chould do other things here while we are waiting
            // for HTTP request to complete

            // Task continuation
            return httpTask.ContinueWith((Task<HttpResponsMessage> antecedent) => {
                return antecedent.Result.Content.Headers.ContentLength;
            })
        }
    }
}

Where:

  • Objective of method GetPageLength: use a System.Net.Http.HttpClient object to request the contents of the Apress home page and returns its lengths.
  • Task continuation: key of this async method
  • .NET represent work that can be done asynchronously as Task.
    • Task object are strongly typed based on result produced by background work.
    • client.GetAsync("..") returns a Task<HttpResponseMessage> (i.e. type of httpTask), which indicates that the request will be performed in background and result of request will be of type HttpResponseMessage.
    • Detail of MVC async methods are in Chap19
  • Task continuation is most mind-boggling part, it's .NET mechanism to specify what happen when background task is completed.
    • Step 1: httpTask is used to get HttpResponseMessage object. The returned object has .ContinueWith method
    • Step 2: .ContinueWith method use lambda expression to return length of the content as a property.
    • Double return: 1st return specify that Task<HttpResponseMessage> object is returned; 2nd return specify when task is complete, the length of ContentLength header will be returned.
  • No need to fully understand this example. It's illustration of complex async operation in previous .NET Framework

4.9.1 Applying the async and await Keywords

C# two keywords async & await are used to simplify async methods.

Listing 4-33. Using the Async and Await Keywords in the MyAsyncMethods.cs File

using System.Net.Http;
using System.Threading.Tasks;

namespace LanguageFeatures.Models {
  public class MyAsyncMethods {
    public async static Task<long?> GetPageLength() {
      HttpClient client = new HttpClient();
      var httpMessage = await client.GetAsync("http://apress.com");

      // Do other things while waiting for HTTP request to complete

      return httpMessage.Content.Headers.ContentLength;
    }
  }
}

Where:

  • await is used when calling async methods (e.g. .GetAsync(...)). It
    • Step 1: tells C# compiler that we want to wait for the result of Task that returned by GetAsync method
    • Step 2: continue executing other statements in same method.
  • async needed to be assigned on method signature when awit keyword appear in method.
  • Benefit of await & async: we can use return keyword in normal way to produce a result from other methods.