Tasks And Asynchronous Programming in C#

Most of the code we write executes synchronously. In the synchronous method, the code executes in deterministic order, and it is easy to understand. However, the application which executes synchronously produces results very slowly, and it becomes unresponsive for further inputs during the execution. We can resolve this problem through the asynchronous programming where our code process multiple inputs at the same time. The asynchronous code executes at the background that means the asynchronous application can be responsive while processing other input.

Microsoft introduced Task Parallel Library (TPL) for asynchronous programming with .Net 4.0 release. Asynchronous unit of work represented by the Task. Let’s discuss how to achieve asynchronous behaviour through Task Parallel Library in C#.

Open Microsoft Visual Studio 2019 => Create Console .Net Framework application and add the below code.

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

namespace AsynchronousProgrammingExp
{
    class Program
    {
        static int number = 0;
        static void Main(string[] args)
        {
            for (int i = 1; i < 1000; i++)
            {
                number = i;
                Task t = new Task(Display);
                t.Start();
            }

            Console.ReadLine();
        }

        private static void Display()
        {
            Console.WriteLine("Number - " + number.ToString());
        }
    }
}

As you see above, we are calling the Display() method through Task, which should produce asynchronous results. Run the application, and it displays output as below.

 

As shown above, it displays the number in random order, not in deterministic order, which proves the Display() method in the above example called asynchronously.

In the above example, we wrote two lines of code to call a method asynchronously. We can achieve the same result through a single line of code through the Task Factory method.

static void Main(string[] args)
{
      for (int i = 1; i < 1000; i++)
      {
          number = i;
          Task t = Task.Factory.StartNew(Display);
      }

      Console.ReadLine();
}

With .Net 4.5 release, we can make it further simpler through the Run() method of Task class as below.

static void Main(string[] args)
{
      for (int i = 1; i < 1000; i++)
      {
            number = i;                
            Task t = Task.Run(() => Display());
      }

       Console.ReadLine();
}

 

tags: