Monday, July 7, 2014

A Very Simple Example on Asynchronous Programming in ASP.NET 4.5

Tip 5. Use Asynchronous Programming to give speed to your code wherever possible

Today i will show you a very simple example of Asynchronous Programming. This example gives you an idea about how to increase speed of your web application using Asynchronous Programming. Let's start with traditional code and it's result. You can copy and paste this code in your aspx.vb page to understand more.

Imports System.IO
Imports System.Threading.Tasks

Public Class Home
    Inherits System.Web.UI.Page
 Protected Sub Page_Load(ByVal sender As Object, 
                        ByVal e As System.EventArgs) Handles Me.Load
        Dim sw As Stopwatch = Stopwatch.StartNew()


        Dim trainId As Integer = bookTrain()
        Dim hotelId As Integer = bookHotel()
        Dim meetingLocation As String = arrangMeetingLocation()

        Response.Write("<br>Finished all task: " 
                       & sw.ElapsedMilliseconds() / 1000.0)

    End Sub

    Dim rand As New Random(100)

    Private Function bookTrain() As Integer
        Response.Write("<br>booking Tain...")
        Threading.Thread.Sleep(5000)
        Response.Write("<br>booked Train.")

        Return rand.Next()
    End Function

    Private Function bookHotel() As Integer
        Response.Write("<br>booking Hotel...")
        Threading.Thread.Sleep(7000)
        Response.Write("<br>booked Hotel.")

        Return rand.Next()
    End Function

    Private Function arrangMeetingLocation() As String
        Response.Write("<br>arranging meeting location...")
        Threading.Thread.Sleep(4000)
        Response.Write("<br>arranged meeting location.")

        Return "meetingPlaceName"
    End Function
End Class

Result will be:

booking Tain...
booked Train.
booking Hotel...
booked Hotel.
arranging meeting location...
arranged meeting location.
Finished all task: 16.018 seconds


As you can see in above code, there is no dependency on each other. so we can run these all methods parallel.
Now, let's use Asynchronous Programming. See the following code and it's result. You can copy and paste this code in your aspx.vb page to understand more.
Imports System.IO
Imports System.Threading.Tasks

Public Class Home
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, 
                   ByVal e As System.EventArgs) Handles Me.Load
        Dim sw As Stopwatch = Stopwatch.StartNew()

        Dim trainTask As Task(Of Integer) = 
             Task.Factory.StartNew(Of Integer)(Function() bookTrain())

        'Each Task will start new thread, so it will run parallel.'
        Dim hotelTask As Task(Of Integer) = 
             Task.Factory.StartNew(Of Integer)(Function() bookHotel())

        Dim meetingLoc As Task(Of String) = 
             Task.Factory.StartNew(Of String)(Function() arrangMeetingLocation())

        Response.Write(String.Format(
                  "<br>train Id: {0}, hotel Id: {1}, meeting Loc: {2}", 
                  trainTask.Result, hotelTask.Result, meetingLoc.Result))

        'If you do not write result '
        'and you want to wait until task completed, '
        'write following line'
        'Task.WaitAll(trainTask, hotelTask, meetingLocId)'

        Response.Write("<br>Finished all task: " 
                    & sw.ElapsedMilliseconds() / 1000.0)

    End Sub

    Dim rand As New Random(100)

    Private Function bookTrain() As Integer
        Response.Write("<br>booking Tain...")
        Threading.Thread.Sleep(5000)
        Response.Write("<br>booked Train.")

        Return rand.Next()
    End Function

    Private Function bookHotel() As Integer
        Response.Write("<br>booking Hotel...")
        Threading.Thread.Sleep(7000)
        Response.Write("<br>booked Hotel.")

        Return rand.Next()
    End Function

    Private Function arrangMeetingLocation() As String
        Response.Write("<br>arranging meeting location...")
        Threading.Thread.Sleep(4000)
        Response.Write("<br>arranged meeting location.")

        Return "meetingPlaceName"
    End Function
End Class

Result will be:

booking Tain...
booking Hotel...
arranging meeting location...
arranged meeting location.
booked Train.
booked Hotel.
train Id: 2080427802, hotel Id: 341851734, meeting Loc: meetingPlaceName
Finished all task: 7.003 seconds

No comments:

Post a Comment

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...