a blog for those who code

Wednesday 23 March 2016

Basic introduction to Asynchronous Programming in .NET Application

In this post we are going to discuss about Asynchronous Programming in .NET Application. Asynchronous operation means that the operation runs independent of other processes i.e. in simple terms simultaneous processing.

As far as C# is concern program starts execution from the main method and it terminates when the method returns, whatever operations happens in between are all synchronous i.e. one after another (Synchronous Programming). If we need to do the same thing using asynchronous programming, it will executes all the operations simultaneously thus avoiding blocking of main thread which can be achieved using Task or Thread.


We will be using Task Based Asynchronous Programming which is based on Task and Task<TResult> which is used for asynchronous operations. It provides several methods for initiation and completion as asynchronous operation.

Creating a Task

Task represents an Asynchronous operation. We will be creating our task using Task.Run<T> method which queues the specified work on the thread pool and returns a Task object that represents that work. The simplest task which you can create is shown below where we are creating a task to make our application sleep for 5 seconds.

Task.Run(() => Thread.Sleep(5000));

Now you may ask me whats the difference between Task and Thread. Task is something which is complete process whereas Thread is one of the possible workers or operations which performs the Task.

Lets create a function which calls Thread.Sleep(5000) and then give a sum of two numbers

public int func(int a, int b)
{
  Thread.Sleep(5000);
  return a + b;
}

Now we will create a task around the above function and wrap it with an asynchronous method. This function will return the Task object.

public Task<int> funcTask(int a, int b)
{
  return Task.Run<int>(() => {
    return func(a, b);
  });
}

"Async" and "Await" Keywords

Async keyword is used in front of a function to make it as a asynchronous function whereas Await keyword is used if we want to call any function asynchronously. In the below function we are using async keyword to make it asynchronous function. When you call this function it starts executing until it encounters await keyword. As soon as it reaches await keyword it waits for the funcAsync function to be finished but the control returns to the caller of the Async function.

public async void funcAsync()
{
  var a = await funcTask(5,6);
  Console.WriteLine("Called FuncAsync " + a);
}

The control will return to the caller of the Async function only if its long running task. If the task is already finished its execution and the result is available, the code will continue executing on the same thread. So when you run the below code :

var a = func(5, 6);
Console.WriteLine("Called Func " + a);
funcAsync();
var c = func(5, 6);
Console.WriteLine("Called Func " + c);

It starts executing the func amd after 5 seconds you will get the result. Now by the next 5 seconds you will get the output from both func and funcAsync because both the method ran almost parallel without blocking each other execution.

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment