ASP Lock and Unlock Methods in ASP.NET using VB.NET

In this article you will learn about Application.Lock and Unlock methods in ASP.NET.
  • 5821

ASP.NET Lock Method

The Lock method blocks other users from modifying the variables stored in the application object. It ensure that only one client at a time can modify the application variables.

ASP.NET UnLock Method

The Unlock method enables other users to modify the variables stored in the application object after it has been locked using the Lock method. If user do not call the Application.Unlock method explicitly, the server unlocks the locked application object when the .asp file ends or times out.

In the following example, we use the lock method prevents more than one user at a time from accessing the variable page counter and then the unlock method which enables other users to access the variables in the application.

Default.apsx (Lock Method) 

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
  <form id="form1" runat="server">
       The page has been visited
       <asp:Label ID="myLabel" runat="server" />


Partial Class _Default
   Inherits System.Web.UI.Page
   Protected Sub Page_Load(ByVal sender As Object, _
   ByVal e As System.EventArgs) Handles Me.Load
       If Application("PageCounter") >= 10 Then
       End If
       If Application("PageCounter") Is Nothing Then
       End If
       myLabel.Text = Application("PageCounter")
   End Sub
End Class


The page has been visited 1 times!

Default.apsx (UnLock Method) 

<%@ Page Language="vb" %>
    <script runat="server">
       Sub Page_Load()
          Application("Counter") = 1
          Message.Text = "Counter = " & Application("Counter")
       End Sub
    <asp:label id="Message" runat="server"/>


Counter = 1

Note: A page doesn't need to lock the application object to edit the application collection. If one page tries to edit the application collection without locking and at the same time second page also tries to edit the collection, no error is sent by IIS and the Application object ends up in an inconsistent state.


More Articles

© 2020 DotNetHeaven. All rights reserved.