What is Asynchronous Programming? (part 2)
In asynchronous programming, the code gets executed in a thread without having to wait for an I/O-bound or long-running task to finish. For example, in the asynchronous programming model, the
Microsoft recommends Task-based Asynchronous Pattern to implement asynchronous programming in the .NET Framework or .NET Core applications using async , await keywords and Task or Task<TResult> class.
Now let's rewrite the above example in asynchronous pattern using
In the above example, the
The
Now, the program starts executing from the
In asynchronous programming, the code gets executed in a thread without having to wait for an I/O-bound or long-running task to finish. For example, in the asynchronous programming model, the
LongProcess()
method will be executed in a separate thread from the thread pool, and the main application thread will continue to execute the next statement.Microsoft recommends Task-based Asynchronous Pattern to implement asynchronous programming in the .NET Framework or .NET Core applications using async , await keywords and Task or Task<TResult> class.
Now let's rewrite the above example in asynchronous pattern using
async
keyword.In the above example, the
Main()
method is marked by the async
keyword, and the return type is Task
. The async
keyword marks the method as asynchronous. Note that all the methods in the method chain must be async
in order to implement asynchronous programming. So, the Main()
method must be async
to make child methods asynchronous.The
LongProcess()
method is also marked with the async
keyword which makes it asynchronous. The await Task.Delay(4000);
holds the thread execute for 4 seconds.Now, the program starts executing from the
async Main()
method in the main application thread. The async LongProcess()
method gets executed in a separate thread and the main application thread continues execution of the next statement which calls ShortProcess()
method and does not wait for the LongProcess()
to complete.