Asynchronous Methods in C#


Async and Await are the two keywords that help us to program asynchronously. An async keyword is a method that performs asynchronous tasks such as fetching data from a database, reading a file, etc., they can be marked as “async”. Whereas await keyword making  “await” to a statement means suspending the execution of the async method it is residing in until the asynchronous task completes. After suspension, the control goes back to the caller method. Once the task completes, the control comes back to the states where await is mentioned and executes the remaining statements in the enclosing method.

Below Example will show while calling async method with await keyword will wait the function to complete execution.

AsyncAndSyncMethods.cs

using System;

namespace CSharpPractices
{
    internal class AsyncAndSyncMethods
    {
        // Synchronos Method
        public void DisplayResult()
        {
            for (int i = 0; i <= 3; i++)
            {
                Task<string> add = Display();
                Console.WriteLine("Addition {0}", add.Result);
            }

            for (int i = 0; i <= 3; i++)
            {
                Task<int> sub = Subtraction(2, 4);
                Console.WriteLine("Subtraction {0}", sub.Result);
            }
        }

        // ASynchronos Method
        private async Task<string> Display()
        {
            Task<int> data = await Task.FromResult(Addition(2, 4));

            if (data.Result == 6)
            {
                return "Result is True";
            }
            else
            {
                return "Result is False";
            }
        }

        // ASynchronos Method
        private async Task<int> Addition(int a, int b)
        {
            return await Task.Run(() => a + b);
        }

        // ASynchronos Method
        private async Task<int> Subtraction(int a, int b)
        {
            return await Task.Run(() => a - b);
        }
    }
}

Program.cs

using CSharpPractices;
using System;

namespace CsharpPractices
{
    public class Program
    {
        public Program()
        {

        }

        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.WriteLine();

            AsyncAndSyncMethods asyncAndSyncMethods = new AsyncAndSyncMethods();
            asyncAndSyncMethods.DisplayResult();

            Console.ReadKey();
        }
    }
}

Output for above code:



Example 2:

Creating two threads with async method will execute parallelly.

AsyncAndSyncMethods.cs

using System;

namespace CSharpPractices
{
    internal class AsyncAndSyncMethods
    {
        // const need to be initiated while declaration but readonly can be initiated by Constructor
        // Const is a compile-time constant, while readonly is a runtime constant.
        //private const string folderPath = "D:\\Projects\\CoreNet\\CSharpPractices\\Files\\ReadPath\\";
        private readonly string folderPath;
        public AsyncAndSyncMethods()
        {
            folderPath = "D:\\Projects\\CoreNet\\CSharpPractices\\Files\\ReadPath\\";
        }

        public void CallingReadFilesMethod()
        {
            Thread.Sleep(100);

            var task1 = ReadFiles("Task 1"); // Task 1
            var task2 = ReadFiles("Task 2"); // Task 2

            Console.WriteLine("Tasks Are Executing");
        }

        // ASynchronos Method
        private async Task ReadFiles(string task)
        {
            await Task.Run(() =>
            {
                Console.WriteLine("Started Reading Files..");
                foreach (string file in Directory.EnumerateFiles(folderPath, "*.txt"))
                {
                    string contents = File.ReadAllText(file);
                    string[] content = contents.Split("\n");
                    Console.WriteLine("Task Type: {0}", task);
                    Console.WriteLine("Reading Completed For the File: {0}", file);
                }
                Console.WriteLine("Completed Reading Files..");
            });
        }
    }
}


Program.cs


using CSharpPractices;
using System;

namespace CsharpPractices
{
    public class Program
    {
        public Program()
        {

        }

        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.WriteLine();

            AsyncAndSyncMethods asyncAndSyncMethods = new AsyncAndSyncMethods();
            asyncAndSyncMethods.CallingReadFilesMethod();

            Console.ReadKey();
        }
    }
}



Output for above example:



Using Wait Function


By using wait function we can prevent parallel execution, Like below example.

ReadFiles("Task 1").Wait(); // Task 1
ReadFiles("Task 2").Wait(); // Task 2

Output when wait function is used:





Contact Form