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.
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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
The page has been visited
<asp:Label ID="myLabel" runat="server" />
times!
</div>
</form>
</body>
</html>
Default.aspx.vb
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
Application.Remove("PageCounter")
End If
If Application("PageCounter") Is Nothing Then
Else
Application.Lock()
Application.UnLock()
End If
myLabel.Text = Application("PageCounter")
End Sub
End Class
Output
The page has been visited 1 times!
Default.apsx (UnLock Method)
<%@ Page Language="vb" %>
<html>
<head>
<script runat="server">
Sub Page_Load()
Application.Lock()
Application("Counter") = 1
Application.UnLock()
Message.Text = "Counter = " & Application("Counter")
End Sub
</script>
</head>
<body>
<asp:label id="Message" runat="server"/>
</body>
</html>
Output
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.