ASP Best Practices |
Browser users often request an ASP page, then move on before the requested page has finished processing. Use the Response.IsClientConnected property to determine the connection status of the target browser. If the target browser is no longer connected, cut off ASP page processing to avoid wasting server resources.
The following ASP page demonstrates the use of the Response.IsClientConnected property to end execution of an ASP application (the code uses many seconds of CPU time, so test it on a system where it will not impact production performance):
<%@ LANGUAGE="VBSCRIPT" %>
<%
Function IsConnectedAfter(Seconds)
Dim StartTime 'time the function started
Dim PauseTime 'time the pause loop started
'Use PerfMon to monitor the CPU cycles on the Web server. You
'will notice that if you click STOP in the browser, the CPU
'will settle down sooner than if the loop had continued.
IsConnectedAfter = True
StartTime = Now
Do While DateDiff("s", StartTime, Now) < Seconds
PauseTime = Now
Do While DateDiff("s", PauseTime, Now) < 1
'Do Nothing.
Loop
Response.Write "."
If Response.IsClientConnected = False Then
IsConnectedAfter = False
Exit Function
End If
Loop
End Function
%>
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual InterDev 1.0">
<META HTTP-EQUIV="Content-Type" content="text/html; charset=iso-8859-1"> <TITLE>Document Title</TITLE>
</HEAD>
<BODY>
<H1>!!! WARNING !!!</H1>
<P>This page has code in it that may use <B>100% CPU cycles</B> for at least 30 seconds. Do not run this code on a production server. Restrict its use to a test server.
<P>Use SysMon to monitor the CPU cycles on the Web server. Press STOP in the Web browser, and you will see that the CPU cycles will settle down sooner than they would have without checking the IsClientConnected property.
<HR>
<%
If IsConnectedAfter(30) then
Response.Write "<P>The client is still connected</P>"
Else
'The browser is no longer connected. This would be a
'good place to abort any transactions, clean up any
'variables, and so forth.
End If
%>
</BODY>
</HTML>
IsClientConnected will only work if Response is buffered.