C# Async Await Implementation Examples on Console App, Win Form and Asp.Net Web App

This post gives examples to use async and await in order to process something asynchronously.

Examples will be presented as Console App, Win Form and Asp.Net Web App.

Taking a definition reference of Async & Await from https://msdn.microsoft.com/en-us/library/hh191443(v=vs.120).aspx :
You can avoid performance bottlenecks and enhance the overall responsiveness of your application by using asynchronous programming. However, traditional techniques for writing asynchronous applications can be complicated, making them difficult to write, debug, and maintain.

Visual Studio 2012 introduces a simplified approach, async programming, that leverages asynchronous support in the .NET Framework 4.5 and the Windows Runtime.
The compiler does the difficult work that the developer used to do, and your application retains a logical structure that resembles synchronous code.
As a result, you get all the advantages of asynchronous programming with a fraction of the effort.

Async Await on Console App

  1. Create a Console application project
  2. Add new Item, Class named TestCls.
    using System.Threading.Tasks;
    ...
    ...
    
     public class TestCls
     {
     public async Task sayHelloAsync()
    {
           await Task.Delay(3000);   
           string strdata = "Hello world async method";
           Console.WriteLine(strdata);
     }
    
     public void sayHelloSync()
     {
      System.Threading.Thread.Sleep(1000);
      string strdata = "Hello world synchronous method";
       Console.WriteLine(strdata);
     }
           
     }
    

    This class just perform to echo string value to console of both asynchronous and synchronous methods.
    We have await Task.Delay(...) to delay the process for demonstration purposes.

  3. Main program source code.
    using System.Threading.Tasks;
    ...
    ...
    static void Main(string[] args)
    {
    	
    	Console.WriteLine("Line before callTestCls async call");
    	callTestCls();
    	Console.WriteLine("Line after callTestCls async call");
    
    	Console.WriteLine("Line before MakeSyncMethodAsynchronous call");
    	MakeSyncMethodAsynchronous();
    	Console.WriteLine("Line after MakeSyncMethodAsynchronous call");
    	Console.ReadLine();
    }
    
    static private void callTestCls()
    {
    	TestCls tcls = new TestCls();
    	tcls.sayHelloAsync().ConfigureAwait(false);
    }
    
    static void MakeSyncMethodAsynchronous()
    {
    	Task.Factory.StartNew(() =>
    	 {
    		 TestCls tcls = new TestCls();
    		 tcls.sayHelloSync();
    
    	 });
    
    }
    

    callTestCls() method implements TestCls.sayHelloAsync() async method and there is ConfigureAwait(false) to make sure method runs asynchronously.

    MakeSyncMethodAsynchronous() makes Sync method run as asynchronous with help of Task.Factory.StartNew(..)

  4. Test your code and the result is shown on below screen shot

    All statement lines i.e “Line before & after callTestCls async call” also “Line before & after MakeSyncMethodAsynchronous call” are shown immediately which means both methods callTestCls() and MakeSyncMethodAsynchronous() are run asynchronously.

Async Await on Win Form

This app copies file from source to destination asynchronously and so the UI is not blocking while copy is in progress.

  1. Create a Windows Form App project
  2. Add new Item, Form. Below pic is Form design


    There is “Type anything below to test UI is not blocking” textbox to test the UI in the middle of copy process.
  3. Form1 source code below:
    using Microsoft.VisualBasic.FileIO;
    using System.Threading.Tasks;
    ...
    ...
    
    public frmCopyPasteAsync()
    {
    	InitializeComponent();
    }
    
    private void frmCopyPasteAsync_Load(object sender, EventArgs e)
    {
    	
    }
    
    private void btnCopy_Click(object sender, EventArgs e)
    {
    	string SourceFile = txtSourceFile.Text;
    	string DestFile = txtDestFile.Text;
    	copyAsync(SourceFile, DestFile).ConfigureAwait(false);
    }
    
    private async Task copyAsync(string SourceFile, string DestFile)
    {
       
    	await Task.Factory.StartNew(() =>
    	{
    		try
    		{
    			FileSystem.CopyFile(SourceFile, DestFile, UIOption.AllDialogs, UICancelOption.ThrowException);
    		} catch (OperationCanceledException ex)
    		{
    			MessageBox.Show("Copy file cancelled");
    		}
    	});
       
    }
    

    We use FileSystem.CopyFile(SourceFile, DestFile, UIOption.AllDialogs, UICancelOption.ThrowException); to copy file. It needs reference of Microsoft.VisualBasic in order to use the method.

    As default, the copy process will block the UI thread as a caller but we implement await and async to make it asynchronous.

  4. Test by running the application. I suggest it by copy large file to see what happens. Right after you click “Start Copy” button then please type anything in “Type anything below to test UI is not blocking” textbox to see whether UI is not blocking.

Async Await on Asp.Net Web App

The web app demonstrate uploading several images. The uploading method uses Task.Factory.StartNew(..) to implement async & await.

  1. Create a Web App Empty project
  2. Add new Item, WebForm. Below is WebForm source code
    <%@ Page Async="true"  Language="C#" AutoEventWireup="true" CodeBehind="UploadImages.aspx.cs" Inherits="WebAsyncAwait.UploadImages" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title> Upload Images Async Demo </title>
    </head>
    <body>
        
        <form id="form1" runat="server">
            Upload Images Async Demo <br /><br />
           
        <asp:FileUpload ID="FileUpload1" runat="server" /> &nbsp; <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
        <asp:FileUpload ID="FileUpload2" runat="server" /> &nbsp; <asp:Label ID="Label2" runat="server" Text=""></asp:Label><br />
        <asp:FileUpload ID="FileUpload3" runat="server" /> &nbsp; <asp:Label ID="Label3" runat="server" Text=""></asp:Label><br /><br />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
               
        </form>
        
    </body>
    </html>
    

    We have three FileUpload components to upload images simultaneously. Also there is Async="true" in Page directive to enabled async & await in a code file.

  3. Below is code *.cs file. The upload procedure is taken from MSDN https://msdn.microsoft.com/en-us/library/ms227669.aspx :
    using System.Threading.Tasks;
    ...
    ...
    protected void Page_Load(object sender, EventArgs e)
    {
    
    }
    
    protected async void btnUpload_Click(object sender, EventArgs e)
    {
    	await UploadFileAsync(FileUpload1, Label1);
    	await UploadFileAsync(FileUpload2, Label2);
    	await UploadFileAsync(FileUpload3, Label3);
    }
    
    private async Task UploadFileAsync(FileUpload fileUpload, Label label)
    {
    	
    	await Task.Factory.StartNew(() =>
    	 {
    		 bool fileOk = false;
    		String path = Server.MapPath("~/TempImages/");
    	
    		if (fileUpload.HasFile)
    		{
    			String fileExtension =
    			System.IO.Path.GetExtension(fileUpload.FileName).ToLower();
    			String[] allowedExtensions =
    				{".gif", ".png", ".jpeg", ".jpg"};
    			for (int i = 0; i < allowedExtensions.Length; i++)
    			{
    				if (fileExtension == allowedExtensions[i])
    				{
    					fileOk = true;
    				}
    			}
    
    			 if (fileOk)
    			 {
    				 try
    				 {
    					 fileUpload.PostedFile.SaveAs(path
    						 + fileUpload.FileName);
    				   
    					 label.Text = "File uploaded!";
    				 }
    				 catch (Exception ex)
    				 {
    					 label.Text = label.Text + "File could not be uploaded.";
    				 }
    			 }
    			 else
    			 {
    				 label.Text = "Cannot accept files of this type.";
    			 }
    		 }
    	   
    		
    	});
    }
    
    	
    }
    

    If upload is succeeded then “File uploaded!” message appear in related label.

    However the upload process is still done serially since next upload will be processed after first upload has done even though we use async & await.

    We need ajax processes in web application in order to do asynchronously. There is more suitable components to do upload asyncly i.e AsyncFileUpload.
    Please check at my post about it at https://gugiaji.wordpress.com/2012/05/14/upload-file-with-asp-net-asyncfileupload-ajax-control-inside-modalpopupextender.

    Above async & await method is shown for demonstration purpose. You may find another cases that more suitable using Async & Await in web app.

Regards,
Agung Gugiaji

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s