About

Tuesday, September 24, 2019

Async and await  C# .Net


What is Async C#?

async functionality/methods runs/executes until it reaches it's first await functionality and until the awaited task is complete.

Async key will support only when it modifies a method and lambda expression or anonymous functionality.

Example 1 :

static void Main(string[] args)
        {
            Int32 VariableName = 0;
            Console.WriteLine("GetTaskAsync1 - Started  Thread ID " + System.Threading.Thread.CurrentThread.ManagedThreadId);
            GetTaskAsync1();
            Console.WriteLine("GetTaskAsync1 - End  Thread ID " + System.Threading.Thread.CurrentThread.ManagedThreadId);

            Console.Read();
        }

        static async Task GetTaskAsync1()
        {
            Console.WriteLine("GetTaskAsync2 - Started  Thread ID " + System.Threading.Thread.CurrentThread.ManagedThreadId);
            int result = await GetTaskAsync2();
            Console.WriteLine("result : "+ result);
            Console.WriteLine("GetTaskAsync2 - End  Thread ID " + System.Threading.Thread.CurrentThread.ManagedThreadId);
        }
        static async Task<int> GetTaskAsync2()
        {
            int count = 0;
            for (int i = 0; i < 1000; i++)
            {
                count++;
            }
            return count;
        }
    }

Conclusion :  if we use async and await key then the functionality will run in synchronous action and the functionality will run in background thread.


Please add the comments then I can improve the blog thank you



0 comments:

Post a Comment