Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Async and await in c# example

Suggested Videos 
Part 98 - Anonymous methods in c#
Part 99 - Lambda expression in c#
Part 100 - Func delegate in C#

In this video we will discuss async and await keywords and their purpose with an example.

Let us create a simple Windows Forms Application that counts the number of characters in a given file. Let us assume the file is very big and it takes around 5 seconds to read and count the number of characters in the file. When the "Process File Button" is clicked, the application should display the message "Processing File. Please wait"



c# asynchronous programming example



As soon as the application finishes processing the file it should display the the number of characters as shown below.

async await example c#

Another improtant requirement is that the application should remain responsive throughout the entire process, i.e when the application is busy processing the file the application should not hang and we should still be able to interact with the application. We should be able to click with in the other controls on the form, move the form around on the screen, resize it if required etc.

Let us first create the Windows Forms Application without using async and await keywords and see how it behaves. Here are the steps.

1. In your C: drive, create a new folder. Name it Data. In the folder create a new Text Document. Name it Data.txt. Type some text in the file and save it. The application that we are going to create, counts the number of characters in this file.

2. Create a New "Windows Forms Application". Name it AsyncExample.

3. Drag and Drop a "Button" on the Form and set the following properties
   Name = btnProcessFIle
   Font - Size = 10
   Text = Process File

4. Drag and Drop a "Label" on the Form and set the following properties
   Name = lblCount
   Font - Size = 10
   Text = ""

5. Double Click on the "Button" control to generate the "Click" event handler

6. Copy and paste the following code in Form1.cs

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AsyncExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private int CountCharacters()
        {
            int count = 0;
            // Create a StreamReader and point it to the file to read
            using (StreamReader reader = new StreamReader("C:\\Data\\Data.txt"))
            {
                string content = reader.ReadToEnd();
                count = content.Length;
                // Make the program look busy for 5 seconds
                Thread.Sleep(5000);
            }

            return count;
        }

        private void btnProcessFIle_Click(object sender, EventArgs e)
        {
            lblCount.Text = "Processing file. Please wait...";
            int count = CountCharacters();
            lblCount.Text = count.ToString() + " characters in file";
        }
    }
}

7. Run the application and click the "Process File" button. You will notice the following problems.
  • The application does not display the status message i.e "Processing file. Please wait."
  • While the application is busy processing the file, it becomes unresponsive. You cannot move the form window or resize it.
These problems can be very easily fixed by using the async and await keywords. Notice only the btnProcessFIle_Click() event handler method needs to change.

// Make the method async by using the async keyword
private async void btnProcessFIle_Click(object sender, EventArgs e)
{
    // Create a task to execute CountCharacters() function
    // CountCharacters() function returns int, so we created Task<int>
    Task<int> task = new Task<int>(CountCharacters);
    task.Start();

    lblCount.Text = "Processing file. Please wait...";
    // Wait until the long running task completes
    int count = await task;
    lblCount.Text = count.ToString() + " characters in file";
}

Now, when we click the "Process File" button, notice
  • The application displays the status message ("Processing file. Please wait") immediately.
  • Even when the application is busy processing the file, it is responsive. You can move the form window around or resize it.
So what is the use of async and await keywords in C#
async and await keywords are used to create asynchronous methods. The async keyword specifies that a method is an asynchronous method and the await keyword specifies a suspension point. The await operator signalls that the async method can't continue past that point until the awaited asynchronous process is complete. In the meantime, control returns to the caller of the async method.

An async method typically contains one or more occurrences of an await operator, but the absence of await expressions doesn’t cause a compiler error.

You may have a few questions at this point. 
1. Can't we achieve the same thing using a Thread. 
2. What is the difference between a Thread and a Task
3. When to use a Task over Thread and vice-versa

We will discuss all these in a later video.

10 comments:

  1. Very Good Explanation. Thanks Venkat.

    ReplyDelete
  2. Hello Sir,

    Would you please discuss the following topics in detail:

    TPL, TPL DATAFLOW, Difference and relation between TPL and Thread and TPL DATAFLOW.

    Thanks

    ReplyDelete
  3. Venkat,
    How do you do? Nowadays you are not so frequent like earlier. I think you are busy with you job.

    I request you to describe LINQ vs PLINQ as you are discussing asynchronous programming.



    ReplyDelete
  4. I understand it but I am looking an example in Web Page.

    ReplyDelete
  5. Venkat,
    You have explained great
    But I am looking this example for web page not for windows or console. Can you please help me?

    Thanks

    ReplyDelete
  6. I have doubt, how does the async work?
    Initially I used to though whenever the async method find await, it will be creating the new thread (creating new thread will keep the UI thread free) and later after completion the new thread will join with the UI thread?

    But to a surprise I found, await call do not create new thread? If it will not create the new thread how our UI thread is free/responsive.

    Please help.

    ReplyDelete
  7. there is an exeption that says:
    Error CS1061 'Task' no contiene una definición para 'GetAwaiter' ni se encuentra ningún método de extensión 'GetAwaiter' que acepte un primer argumento del tipo 'Task' (¿falta alguna directiva using o una referencia de ensamblado?)

    ReplyDelete
  8. @Carlos, use .net 4.5 framework for your project. Also, there is a typo in this example: private void btnProcessFIle_Click(object sender, EventArgs e) should be btnProcessFile. Small i in word File

    ReplyDelete
  9. here is an exeption that says:
    Error CS1061 'Task' no contiene una definición para 'GetAwaiter' ni se encuentra ningún método de extensión 'GetAwaiter' que acepte un primer argumento del tipo 'Task' (¿falta alguna directiva using o una referencia de ensamblado?)

    ReplyDelete
  10. I had this issue in one of my projects, where I found that I had set my project's .Net Framework version to 4.0 and async tasks are only supported in .Net Framework 4.5 onwards.

    I simply changed my project settings to use .Net Framework 4.5 or above and it worked.

    ReplyDelete

It would be great if you can help share these free resources