Thursday 1 December 2016

async and await keyword in C#

async: It is used to specify a method, lambda expression, or anonymous method to be asynchronous, that execute in the background.
https://msdn.microsoft.com/en-us/library/hh156513.aspx


await: this operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes.
https://msdn.microsoft.com/en-us/library/hh156528.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace async_await_console_application_Csharp
{
 


    class Program
    {
        void task1()
        {
            Console.WriteLine("task 1 completed" );
        }

        async void task2async()
        {
            var result = await Task.Run(() => task2());
        }

        bool task2()
        {
             
            Console.WriteLine("task 2 started");
            System.Threading.Thread.Sleep(2000);
            Console.WriteLine("task 2 completed");
            return true;
        }

        void task3()
        {
            Console.WriteLine("task 3 complete");
        }


        async Task task4async()
        {
            var result = await Task.Run(() => {
                Console.WriteLine("task 4 started");
                Console.WriteLine("task 4 Completed");
                return true;
            });
            return result;
        }



        static void Main(string[] args)
        {
            Program p = new Program();
            p.task1();
            p.task2async();
            p.task3();
            Task.Run(() => p.task4async());
            Console.Read();

        }

        //We can not use async modifier with Main method in console application C#. it will give us build failed without any reason.
        //static async void Main(string[] args)
        //{
        //    Program p = new async_await.Program();
        //    p.task1();
        //    p.task2async();
        //    p.task3();
        //    var a = await p.task4async();
        //    Console.Read();
        //}
    }
}