Async and Await
Async and await are the two most important keywords in C# while doing asynchronous programming. Async keyword is used to in the signature of a method to denote that this method will be executed asynchronously, if you are making a method async then you need to use await keyword in the method. Await keyword is used to denote that the method execution will not processed unless all the task which needs to be executed are complete.
You will get an better idea of Async and Await keyword with below example. As shown in the below example we have run the same code synchronously and asynchronously, and we have captured the time required for both the codes to be executed. As you can see we are iterating through a same list of string 4 times to find a match for a particular string, and then we have added a 1000 millisecond sleep time between execution of each iteration.
If you see the time taken by running the code asynchronously and synchronously then you will find out that time taken for asynchronous execution of code is much less than the synchronous execution of code. Please find the output of console window below.
So in the asynchronous execution of code while executing the executeList method code, we have created different task for iteration and then that other tasks do not wait for the first task to get complete, all the tasks starts executing parallelly and the time taken to execute the whole code is the maximum taken by an single iteration. In synchronous code execution, it waits for the first iteration of the code to be complete and then the second iteration of the code start executing so it has to wait for 1000 millisecond which is added by us before start executing the other code. You can think the wait of 1000 millisecond added by us any other action which needs to be executed in the practical example of the code.
So to conclude asynchronous coding gives you an edge while executing the code but it needs to be used carefully and over use of asynchronous code and no proper use of asynchronous coding can led to system degradation.
Thank you for reading this blog and please read my other blogs on different topics related to C#. If you any other query related to C#, .NET or jQuery or to provide any feedback please write to me on prson94@gmail.com and I will try to get back to you as soon as possible.
Thank You...…..
Email Id - prson94@gmail.com
0 comments:
Post a Comment