10. Asynchronous Programming

Asynchronous Programming

An asynchronous operation executes in a thread, separate from the main application thread. When an application calls a method to perform an operation asynchronously, the application can continue executing while the asynchronous method performs its task. Example Let’s take an example to understand this concept. Here, the program accepts user input using the IO library.

import 'dart:io'; 
void main() { 
   print("Enter your name :");            
   
   // prompt for user input 
   String name = stdin.readLineSync();  
   
   // this is a synchronous method that reads user input 
   print("Hello Mr. ${name}"); 
   print("End of main"); 
} 

The readLineSync() is a synchronous method. This means that the execution of all instructions that follow the readLineSync() function call will be blocked till the readLineSync() method finishes execution.

The stdin.readLineSync waits for input. It stops in its tracks and does not execute any further until it receives the user’s input.

Outtput

Enter your name :     
Tom                   

// reads user input  
Hello Mr. Tom 
End of main

when to use asynchronous programming?

The asynchronous programming is used for folloeing scenario:-

  • When we want complete work in quick time.
  • The delay involves waiting for I/O ( disk or network ) operations, not compulation.
  • when many I/O operation are happing at once.