Applications are getting more responsive and user friendly these days.This means that the user should always be kept informed about the status of the application and application should be fast and not get stuck in some long running operation.
Also hardware is getting more powerful day by day.These days it is not unusual to have CPUs having multiple cores.
Normally method execution is synchronous.So if we have 2 method calls as:
void Main() { method1() method2() }
So method1 will execute and after it finishes execution then method2 will execute.
To allow the application to work even when a long running process is executing it needs to be asynchronous.This means that the long running process should not block the main UI thread and should rather get executed on a separate thread.To achieve this asynchronous functionality should be implemented in the application.
Some of the ways to implement asynchronous code are:
- Threads
- Tasks
- async and await keywords
Previously implementing asynchronous code in a application was a complex process.But now with the async and await keywords in c# we can easily implement applications which remains responsive even when waiting for a long running process to complete.
To implement asynchronous operation we can follow the below steps:
1.declare a long running method using the async keyword.This method should return either Task,Task<T> or void
Below we have declared a method called GetResultsAsync
private async Task GetResultsAsync() { }
2. Call the long running operation from within the method using await keyword
Call the method you want to call asynchronously and mark it with the keyword await.In the following method we have called the method FetchById asynchronously by marking it with the keyword await.
At the point in execution when await keyword is encountered the execution returns to the calling method.And when the awaited method finishes execution control returns back to the the point where we call the awaited method.
Its important to remember that we can call only those method asynchronously which returns Task<T> or Task.
private static async Task<int> GetResultsAsync() { //perform operations int a = 2; int b = 1; int c = a + b; WebClient client = new WebClient(); var result = await FetchById(); Console.WriteLine("This is printed from asynchronous method {0}",result); return result; }
3.Implement the method which implements the long running task
Declare the long running method which you need to execute asynchronously.Below we have declared the method FetchById() asynchronously.
Though most of the times the method will implement code which takes really long to execute.Also this method should return Task<T> where T is the data type which needs to be returned to the calling method.
public static Task<int> FetchById() { var coll1 =new string[] { "a", "b", "c", "d" }; return Task.Run<int>(() =>1 ); }
We get the following output after the above code executes
Leave a Reply