C# Async and Await

C# Async and Await Tutorial

Advertisements

This is continuation of article about multi-threading. I previous post i  described basics of multi-threading and how to use threads to perform operations of different cores of CPU.

I this part I’ll focus on Async and Await keyword that are combined to create easy to read asynchronic 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.

Async methods are intended to be non-blocking operations. An await expression in an async method doesn’t block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.

Using only main tread can cause the problem of unresponsive  UI while complicated task is executed. With Async method we can assign this big task to different thread using Task.Run(), making main thread free to use what solve the problem of unresponsive UI.

Lets take a look at example of implementation. This keywords are part of System.Threading.Tasks namespace. In this example I’m using console application.

 

using System;
using System.Threading.Tasks;

class Program
{
  static void Main()
  {
    //Here I create an instance of MyClass
    MyClass a = new MyClass();

    //This calls the async Method
    Task task = a.DoWork();
    //This line is execued after the task is done
    Console.WriteLine("Done");
    Console.ReadLine();
  }
  public class MyClass{
  //This async method contains await method
  public async Task DoWork()
  {
    int res = await Task.FromResult<int>(Iterate(4, 10));

    //This line is executed after the iterations
    Console.WriteLine(res);
  }

  private int Iterate(int initialValue, int numberOfTimes)
  {

  for (int i = 0; i < numberOfTimes; i++)
  {
     initialValue++;
  }
  return initialValue;
  }
}

//Output

//14

//Done</pre>

Async class can have 3 different returns:

  • Task
  • Task<> //Task with generic return value
  • void

 

 

The async and await keywords don’t cause additional threads to be created. Async methods don’t require multithreading because an async method doesn’t run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn’t help with a process that’s just waiting for results to become available.

With these keywords, we run methods in an asynchronous way. Threads are optional. This style of code is more responsive. A network access can occur with no program freeze. This is just a brief introduction to Asynchronous Programming. In next session I’ll try to cover this topic in more details. Stay Awesome!

Author: indiedevart

Indie Games Developer

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