Web developers dilemma with async in C#


Most web developers use asynchronous programming in Javascript. Most of us have done ajax calls and handled callbacks. Probably if there was an alternative (simple) programmers would have preferred a synchronous way of calling api. You can find many questions in Stackoverflow over this. Even though JQuery can do synchronous api calls you still need to code in the same way. I think this is the reason we became familiar with asynchronous programming in Javascript rather than benefit of programming that way.


function GetWebData(){
   var webData;
    jQuery.ajax({
        url: apiUrl,
        success: function(data) {
        webData = data;
    },
    async:false
  });
    return webData;
}




This does work synchronously. But syntax remains same. So we figured out handling the results in success using callbacks. But these lessons remained in Javascript programming. You can hardly see async await keywords in C# (introduced in 2012).

One reason for this - it is hard to think async. We learn lessons step by step. We have classrooms which teach subjects one after other. We write answers in lines. We are conditioned to function this way. So our programs reflect this thinking.

From a different perspective - we are still able to achieve the programming goal without exploiting these. This might be the reason for slow adoption. New dotnet core does force you to adopt these in many cases.

Lets consider C# example now.

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("ProgramStart");
            CallDoSomething();
            Console.WriteLine("Main complete.");
            Console.Read();
        }

        private static async void CallDoSomething()
        {
            await DoSomething();
            Console.WriteLine("Complete of CallDoSomething");
        }

        private static async Task DoSomething()
        {
            await Task.Run(() =>
            {
                System.Threading.Thread.Sleep(1000);
                Console.WriteLine("After delay of 1000");
            });
            Console.WriteLine("Complete of DoSomething");
        }
    }

This will produce output 
ProgramStart
Main complete.
After delay of 1000
Complete of DoSomething
Complete of CallDoSomething

As you observed await forces the program to wait for completion of the async method. This actually helps the programmers write better code without lot of syntax change. Meantime compiler makes rest of method a callback to the async task. Thread is not blocked and no need to break your head about callbacks. Still programmers are slow to exploit this. 

Comments

Popular posts from this blog

ChatGPT for cavemen

Greedy computing with API

Event driven architecture for micro services