Asynchronous programming is used to avoid unnecessary lags in performance. For example, in a synchronous application, if one particular part of a web page takes a long time to load the whole application stalls. However, asynchronously, this can be avoided by allowing other parts of the web page to render whilst the slow part is being resourced. Since C# 5, this has been easy to do and is shown below.
Note that the Run method has an async modifier which allows the await operator to be used within it. Firstly, the GetRandomNumberTask method is called - this is what will be causing the lag in performance. However, crucially the IndependentMethod method runs before the GetRandomNumberTask has completed.
In this example, an artificial delay of 3 seconds is used to simulate a genuine server lag, afterwards a random number between 0 and 1500 is returned.
In the demo used here, a simple console application is used. The Main method (not shown) simply calls the Run method as can be seen below.
Note that the Run method has an async modifier which allows the await operator to be used within it. Firstly, the GetRandomNumberTask method is called - this is what will be causing the lag in performance. However, crucially the IndependentMethod method runs before the GetRandomNumberTask has completed.
In this example, an artificial delay of 3 seconds is used to simulate a genuine server lag, afterwards a random number between 0 and 1500 is returned.
The IndependentMethod method simply tells the user to standby. After 3 seconds have passed the user will be shown a random number in the console.
In a synchronous program, the user would have to wait until the GetRandomNumberTask method has completed before displaying the "Please standby..." method, which clearly would not be fit for purpose.
Comments
Post a Comment