Asynchronous Programming in C Sharp

Synchronous Program Execution

 

Application is executed line by line, one at a time. When a function is called, program execution has to wait until the function returns.

 

Asynchronous Program Execution

 

When a function is called, program execution continues to the next line, without waiting for the function to complete. In asynchronous execution, callback is provided. When execution of the function is finished, method with the callback is called.

 

Difference between Async and Sync :

·         Asynchronous programming improves responsiveness of the application. Used in media players or web browsers. Without asynchronous programming GUI applications would have frozen.

When to use asynchronous? Example usages:

·         Accessing the web

·         Working with files and databases

·         Working with images

Traditionally, we have two different ways to achieve asynchronous programming. First is multi-threading and the other is callbacks. Starting with .Net 4.5, task based asynchronous model is introduced. It is achieved by using Async and Await keywords.

 

Sample application

 

Public partial class MainWindow

{

                Public MainWindow()

                {       InitializeComponent();         }

                Private void Button_Click(object sender, RoutedEventArgs e)

                {        DownloadHtml(“https://www.google.com”);     }

               

 

// Non asynchronous version of the method

                Public void DownloadHtml(string url)

                {

                               Var webClient = new WebClient();

                               Var html = webClient.DownloadString(url);

                               Using (var streamWriter = new StreamWriter(@”c:\projects\result.html”))

                               {

                                               streamWriter.Write(html);

                               }

                }

// Asynchronous version of the method, returns a task object. Add Async at the end of method name.

Public async Task DownloadHtmlAsync(string url)

                {

                               Var webClient = new WebClient();

                               Var html = await webClient.DownloadStringTaskAsync(url);

                               Using (var streamWriter = new StreamWriter(@”c:\projects\result.html”))

                               {

                                               await streamWriter.WriteAsync(html);

                               }

                }

 

DownloadStringTaskAsync method is supported by .Net 4.5 and it is already in the library. Await keyword is marker for the compiler. We make sure the function that has await keyword beforehand is costly. Instead of blocking the thread, it will return to the caller of DownloadHtmlAsync method. So that user interfaces is responsive. At some point downloading task will be completed. After the completion of the task, runtime comes back to the line right after await (streamwriter initialization in the example) and rest of the code will be executed.

 

You can use asynchronous programming in WPF applications all blocking operations such as accessing database, calling web services or accessing the web.

In web applications, user interface is in the browser (client). Blocking operations make the thread busy. Each machine has limited number of threads. If we use async model, controller returns the thread immediately in case of blocking operation. Then thread used to process another request. When thread exits execution, same thread or another thread will come back and complete execution where it is left off. Instead of scaling out by increasing the number of servers, we can scale up with async model.

 

Private async void Button_Click(object sender, RoutedEventArgs e)

{

                var html = await GetHtmlAsync(“https://www.google.com”);

MessageBox.Show(html.Substring(0,10));

// or Asyncronous :

                var getHtmlTask = GetHtmlAsync(“https://www.google.com”);

var html = await getHtmlTask;

MessageBox.Show(html.Substring(0,10));

}

 

// non synchronous

Public string GetHtml(string url)

{

                Var webClient = new WebClient();

                Return webclient.DownloadString(url);

}

 

// Synchronous version

Public async Task<string> GetHtmlAsync(string url)

{

                Var webClient = new WebClient();

                Return await webclient.DownloadStringTashAsync(url);

}

 

Await keyword is not necessary in all cases. Sometimes you can do other work without waiting. Some of the code can be done later, some of it can be done in runtime.

Use await when rest of the method can’t be executed until the result is ready.

Share this Post

Categories

Featured Author