liveBook · Manning

Task

As explained in Pro ASP.NET Core 7, Tenth Edition

Task is the .NET abstraction representing an asynchronous operation that may produce a result when it completes.

A Task represents an asynchronous operation; a typed task such as Task<HttpResponseMessage> or Task<long?> produces a result when it completes. section 5.13.1

For HTTP work, ContinueWith attaches code to run after a task completes. The async and await keywords make consuming its result more natural, while the method still returns a Task. ASP.NET Core action methods can return tasks too. section 5.13.1 section 5.13.2

Listing 5.54 Using the async and await keywords in the MyAsyncMethods.cs file in the Models folder
namespace LanguageFeatures.Models {

   public class MyAsyncMethods {
       
       public async static Task<long?> GetPageLength() {
           HttpClient client = new HttpClient();
           var httpMessage = await client.GetAsync("http://manning.com");
           return httpMessage.Content.Headers.ContentLength;
       }
   }
}

See an async method await an HTTP request and return its content length as Task<long?>. section 5.13.2

Listing 5.55 An asynchronous action method in the HomeController.cs file in the Controllers folder
namespace LanguageFeatures.Controllers {
    public class HomeController : Controller {
        
        public async Task<ViewResult> Index() {
            long? length = await MyAsyncMethods.GetPageLength();
            return View(new string[] { $"Length: {length}" });
        }
    }
}

An action method awaits the helper task before returning a ViewResult. section 5.13.2

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains typed results, continuations, and async/await, but leaves deeper asynchronous and parallel-programming details for further study.
Examples
Demonstrates fetching a web page's content length and awaiting that result in a controller action.
What you can do after
Apply it via async/await to write HTTP helper methods and controller actions that return typed tasks.
How it connects
Connects Task to async/await, continuations, HttpClient, and ASP.NET Core action methods.

Also explained in

Compare how 10 books explain task →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.