Asyncfunctions.md - brainchildservices/curriculum GitHub Wiki

Slide 1

C# Asynchronous Method

C# asynchronous method is a special method that executes asynchronously. C# provides async modifier to make a method asynchronous. It is used to perform asynchronous tasks.

C# await expression is used to suspend the execution of a method.

If a method which uses async modifier does not contain await expression, executes synchronously.

 Note: the async method cannot use ref or out parameters.

Slide 2

C# Asynchronous Method Return Types

An async method can use any one of the following return type.

  • Task
  • Task
  • Void (for event handlers)
  • System.Threading.Tasks.ValueTask

We should add asyncsuffix to the method name because of naming convention. Following is a typical syntax to define asynchronous method.

Slide 3

Syntax

 public async Task<int> ExampleMethodAsync()    
 {    
     // statements    
 }  

We can use System.Net.HttpClient, Microsoft.Azure.EventHub.Core libraries that contain asynchronous operations.

In the following example, we are using using System.Net.Http; namespace to execute an asynchronous task.

This namespace is not available by default, so we need to install it by using the package manager console.

Slide 4

To open console, follow the instruction as we did in the following screenshot.

This will open a console window, where we can pass namespace name to install it in our project. Write the following command, as we did in the following screenshot.

Slide 4 Downwards

  PM> Install-Package System.Net.Http  

After installing it, now we can execute the application.

Slide 5

C# Asynchronous Method Example

  using System;  
  using System.Threading.Tasks;  
  using System.Net.Http;  
  namespace CSharpFeatures  
  {  
      class AsynchronousMethod  
      {  
          static void Main(string[] args)  
          {  
             Task<int> result = add();  
             Console.WriteLine("length: {0}", result.Result);  
          }  
  // Asynchronous method  
          async static Task<int> add()  
          {  
              Task<string> TaskUrl = new HttpClient().GetStringAsync("http://www.brainchildschool.com");  
              string result = await TaskUrl;  
              return result.Length;  
          }  
      }  
  }  

Output

  length: 36006
⚠️ **GitHub.com Fallback** ⚠️