Wednesday, December 28, 2016

Asynchronous programming with async await

A simplified approach for asynchronous programming was introduced with Visual Studio 2012, that leverages asynchronous support in the .NET Framework 4.5 and higher as well as in the Windows Run-time. Here in this approach compiler does all the difficult work and application retains a logical structure that resembles synchronous code. As an advantage we got asynchronous programming with minimal effort.


async and await keywords are used or we can say both are heart of asynchronous programming. By these two keywords you can use .NET Framework or Windows Run-time to create an asynchronous method like you create an synchronous method.


Highlights
 

  • For declaring a method as async put async keyword in from of a method.
  • Create a task to execute some time taking method.
  • await until it finished.

Example

In a windows form application on a button click lets execute a time taking method asynchronously. 



First thing we need to put async key work in button click event.


private async void btnClick_Click(object sender, EventArgs e)

Secondly create a method which take some time to execute. Here we create a method which display a message after 5 second.


private void ShowMessage()
{
     int waitTime = Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds);
     Thread.Sleep(waitTime);
     MessageBox.Show("I am an async message.","Async await demo");
}


Finally, need to create a task and call this method.

    Task task = new Task(ShowMessage);
    task.Start();


And button click must listen for this task to execute.

    await task;


So once we click the button it will execute the ShowMessage method asynchronously and not UI or main thread blocked by this operation. The keyword await will hook the the ShowMessage method with main UI thread. It is typically used if the called method(ShowMessage) return some value that need to captured in main thread.



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

namespace TestAsyncAwait
{
    public partial class frnDemo : Form
    {
        public frnDemo()
        {
            InitializeComponent();
        }

        private async void btnClick_Click(object sender, EventArgs e)
        {
            Task task = new Task(ShowMessage);
            task.Start();

            lblResult.Text = String.Format("Async process start.{0}You will get a message in 5 seconds.", Environment.NewLine);

            await task;
        }

        private void ShowMessage()
        {
            int waitTime = Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds);
            Thread.Sleep(waitTime);
            MessageBox.Show("I am an async message.","Async await demo");
        }
    }
}

Happy Coding ..!!