Implement Synchronization in Application State Using ASP.NET

Application state

Application state is a global storage mechanism that is stored on the server and shared for all users. Does not expire. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages. We can count how many times a given page has been requested by various clients using an application state. The below code defines that.

protected void Page_Load(object sender, System.EventArgs e)

    {

        int count = 0;

        if (Application("Pagecount") != null)

        {

            count = Convert.ToInt32(Application("Pagecount"));

        }

        count += 1;

        Application("Pagecount") = count;

        Label1.Text = " total Page Visited: " + count.ToString() + "Times";

    }

 

Problem with Above code

How to implement Synchronization in application state?

In the above code, a page counter would probably not keep an accurate count. For example, if two clients requested the page at the same time. Then deadlock will occur. We can avoid deadlock occurrence while we updating application variable by multiple users with help of Lock() and UnLock().

Adding the following code with lock and unlock method.

protected void Page_Load(object sender, System.EventArgs e)

    {

        Application.Lock();

        int count = 0;

        if (Application("Pagecount") != null)

        {

            count = Convert.ToInt32(Application("Pagecount"));

        }

        count += 1;

        Application("Pagecount") = count;

        Application.UnLock();

        Label1.Text = "Total Page Visited: " + count.ToString() + "Times";

    }

Ebook Download
View all
Learn
View all