Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
async
await

How to use Async and Await in C#

Educative Answers Team

Async and Await

Async and Await offer ways to implement asynchronous elements into programs. Asynchronous Programming allows portions of code to be run in parallel.

Usage

To define a certain function as an asynchronous function, we will use the async keyword. The await keyword will block the main thread until an asynchronous function successfully or unsuccessfully reaches a conclusion.

using System;
using System.Threading.Tasks;

class AsyncAwait
{
    public static string [] bookList = new string []{"Programming for Beginners", "1984", "Biology"};
    public static string [] lateFee = new string []{"George", "Jack", "Jennifer"};
    static void Main()
    {
        CheckoutBook().GetAwaiter().GetResult();
    }

    static Task<int> CheckAvailability(string bookName)
    {
      string val = Array.Find(bookList, ele => String.Equals(ele, bookName));
      if (val != null) return Task.FromResult(0);
      
      System.ArgumentException argEx = new System.ArgumentException("Book not available");
      throw argEx;
    }

    static Task<int> CheckMembership(string memberName)
    {
      string val = Array.Find(lateFee, ele => String.Equals(ele, memberName));
      if (val == null){
        return Task.FromResult(0);
      }
      System.ArgumentException argEx = new System.ArgumentException("Fee not paid");
      throw argEx;
    }

    static async Task CheckoutBook()
    {
      try
      {
        var checkBook = CheckAvailability("1984");
        var checkFee = CheckMembership("Joel");
        await checkBook;
        Console.WriteLine("Book available");
        await checkFee;
        Console.WriteLine("Member Fee verified");
        Console.WriteLine("Book issued");
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
      }
    }
}

This example simulates a book being checked out from the library. It asynchronously checks whether the book is available and if the member has paid their fee. try, catch blocks are used to check whether or not the async functions have successfully completed. If any of the conditions are not met, the async functions throw an exception.

The async function, CheckoutBook(), calls CheckAvailability() and CheckMembership() to check if the transaction can be authorized. The return statements have return Task.fromResult(0) in order to get rid of the warning the compiler gives when an async function does not use await.

RELATED TAGS

c#
async
await
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring