Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Async Await in C# Example

What is Async And Await In C#

In normal scenario when we use any application, click on a button and then wait for result before we can click on some other button or do any other task, so sometimes we get response really first and we don’t really realize the waiting time, but in some task takes really long to complete and get the response back, until the UI (user interface) is not useable, that is synchronous behavior of an application.

Asynchronous (Async) is just opposite, means we don’t have to wait for any particular task to finish, we can do some other task on same user interface side by side, which is a fantastic features for user experience.

Asynchronous programming is becoming very popular because of this reason, So the reason we write Asynchronous code that allows multiple things to happen at the same time without blocking user interface.

Here are some keywords you need to know while writing any asyc method
Old New Description
task.Wait await task Wait for a task to complete
task.Result await task Get the result of a completed task
Task.WaitAny await Task.WhenAny Wait for one of a collection of tasks to complete
Task.WaitAll await Task.WhenAll Wait for all tasks of a collection to complete
Thread.Sleep await Task.Delay Wait for a period of time
Task constructor Task.Run or TaskFactory.StartNew Create a new task or execute a task

Async Method Example in C#

First I show you an example how you can run a method asynchronously.
Create a simple console application, then create a class called AsycExample
This is simple method that do some calculation and resturn a int number, but calculation takes time. now we call this method asynchronously so my UI is free for other task
static int Calculate()
{
// calculate total count of digits in strings.
int size = 0;
for (int z = 0; z < 100; z++)
{
for (int i = 0; i < 100000; i++)
                {
                    string value = i.ToString();
                    size += value.Length;
                }
            }
            return size;
        }
            

Now write a static method and call the above with await Task.Run
public static async void Execute()
{
// running this method asynchronously.
int t = await Task.Run(() => Calculate());
            Console.WriteLine("Result: " + t);
        } 


Now we call the above Execute() method from our console UI, but while waiting for result we should be able to type something on UI.
Let's test
class Program
    {
        static void Main(string[] args)
        {
            AsycExample.Execute();

            Console.WriteLine("Hello World");

            Console.ReadLine();
        }
    }

If you notice "Hello World" will get printed first, you also can type something while waiting for result.

Here is another example, this loop will run slowly, in between you type something on console, UI is not blocked
public static async Task SlowLoop()
{
await Task.Run(() =>
{
for (int i = 0; i < 10000; i++)
        {
            Thread.Sleep(5000);
            Console.WriteLine(DateTime.Now.Millisecond);
                    
        }
                
    });
}

In above code instead of using Thread.Sleep(5000); we should have written the following lines
        Task wait = Task.Delay(5000);
        wait.Wait(); 
        
Output would have been same,
but there is a difference between Thread.Sleep() & Task.Delay()
You should Use Thread.Sleep when you want to block the current thread.
and write Task.Delay when you want a logical delay, without blocking the current thread

You may also read Async Task in Asp.Net MVC


 
Async Await Example
Learn C# Online Tutorial


Group Training