The following are implemented using static variables:
Copy Code code as follows:
<%@ Page language= "C #"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<script runat= "Server" >
private static int processbar = 0;
private static int totalcount = 100; Set the initial value to prevent 0 from appearing.
protected void Processtask ()
{
By calculating, we can get the value of totalcount, such as querying database
TotalCount = 150;
while (Processbar < totalcount)
{
Processbar + 5;
System.Threading.Thread.Sleep (1000);
}
}
protected void Page_Load (object sender, EventArgs e)
{
if (request.querystring["step")!= null && request.querystring["step"]. Equals (String.Empty) = = False)
{
if (request.querystring["step"). Equals ("1"))
{
Processbar = 0;
System.Threading.Thread Thread = new System.Threading.Thread (new System.Threading.ThreadStart (Processtask));
Thread. Start ();
Response.clearcontent ();
Response.Write (0);
Response.End ();
}
Else
{
Response.clearcontent ();
if (Processbar < TotalCount)
{
Response.Write (Processbar * 100/totalcount);
}
Else
{
Response.Write ("OK");
}
Response.End ();
}
}
}
</script>
<title> on client Display server-side task processing progress bar </title>
<script type= "Text/javascript" >
var http = null;
var count = 1;
var timer = null;
function Createxmlhttp () {
return window. XMLHttpRequest? New window. XMLHttpRequest (): New window. ActiveXObject ("MSXML2.") XMLHTTP ");
}
function showprocess () {
http = createxmlhttp ()
Http.open ("Get", "<%=request.url.tostring ()%>?step=" + (count++) + "&" + date.parse (new Date ()), true;
Http.onreadystatechange = function () {
if (http.readystate = = 4 && http.status = 200)
if ("OK" = = Http.responsetext) {
document.getElementById ("process"). InnerHTML = "complete";
Window.clearinterval (timer);
}
else {
document.getElementById ("process"). InnerHTML = Http.responsetext + "%";
}
}
Http.send (NULL);
}
function StartTask () {
Count = 1;
document.getElementById ("process"). InnerHTML = "0%";
Timer = Window.setinterval ("showprocess ()", 1000);
return false;
}
</script>
<body>
<form id= "Form1" runat= "Server" >
<input type= "button" value= "Start processing long time operation" onclick= "return StartTask ();"/>
<div id= "Process" ></div>
</form>
</body>
This approach is not problematic in the case of a user's access, but is confusing when accessed by multiple users.
This method, which is commonly used, is generally available to meet the requirements:
Copy Code code as follows:
<%@ Page language= "C #"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-
Transitional.dtd ">
<script runat= "Server" >
<summary>
Set global variables so that different methods are used in the
</summary>
private int processbar = 0; Sets the initial state, or represents each step in a series of steps.
private int totalcount = 100; Set the initial value to prevent 0 from appearing.
Private String key;
protected void Processtask ()
{
while (Processbar < totalcount)
{
Processbar = this. Getprocessbar () + 5; This is just a simulation, plus 5 each time.
System.Threading.Thread.Sleep (1000); This is just a long time to simulate the execution process.
SaveData ();
}
}
protected void Page_Load (object sender, EventArgs e)
{
Key = request.querystring["GUID"]; When multiple concurrent requests are used, the client's request is differentiated.
if (String.IsNullOrEmpty (key)) key = Guid.NewGuid (). ToString ();
Processbar = this. Getprocessbar ();
TotalCount = this. Gettotalcount ();
The following is the original decision to determine the different process of the request, is the first request, or update the progress bar request, the implementation method can also be divided into multiple programs to achieve.
if (request.querystring["step")!= null && request.querystring["step"]. Equals (String.Empty) = = False)
{
if (request.querystring["step"). Equals ("1"))
{
Starts a request to perform a task and initiates a lengthy task processing.
Processbar = 0;
By calculating, we can get the value of totalcount, such as querying database, or the sum of several steps of a task.
TotalCount = 200; If it takes 200 steps to complete a task
SaveData ();
System.Threading.Thread Thread = new System.Threading.Thread (new System.Threading.ThreadStart (Processtask));
Thread. Start ();
Response.clearcontent ();
Response.Write (0);
Response.End ();
}
Else
{
Response.clearcontent ();
if (Processbar < TotalCount)
{
Process of output processing
Response.Write (Processbar * 100/totalcount);
}
Else
{
All tasks are completed, output end information, termination of the front-end request.
Response.Write ("OK");
Cache.remove (key);
}
Response.End ();
}
}
Else
{
G.text = key;
if (System.IO.File.Exists (Server.MapPath (key + ". txt"))
{
System.IO.File.Delete (Server.MapPath (key + ". txt"));
}
}
}
<summary>
Get the stage of the execution process
</summary>
<returns></returns>
private int Getprocessbar ()
{
String data = convert.tostring (Cache.get (key));
if (String.IsNullOrEmpty (data))
return 0;
Else
{
return Convert.ToInt32 (data. Split (', ') [0]);
}
}
<summary>
Get the full number of processes
</summary>
<returns></returns>
private int Gettotalcount ()
{
String data = convert.tostring (Cache.get (key));
if (String.IsNullOrEmpty (data))
return 0;
Else
{
return Convert.ToInt32 (data. Split (', ') [1]);
}
}
<summary>
Save the procedure.
</summary>
private void SaveData ()
{
Writelog ();
Cache.Insert (Key, processbar.tostring () + "," + totalcount.tostring ());
}
private void Writelog ()
{
System.IO.StreamWriter SW = new System.IO.StreamWriter (Server.MapPath (key + ". txt"), true);
Sw. WriteLine ("Processbar =" + Processbar + "TotalCount =" + TotalCount + "" + System.DateTime.Now.ToString
());
Sw. Close ();
}
</script>
<title> on client Display server-side task processing progress bar </title>
<script type= "Text/javascript" >
var http = null;
var count = 1;
var timer = null;
var guid = "<asp:literal id= ' G ' runat= ' server '/>";
function Createxmlhttp () {
return window. XMLHttpRequest? New window. XMLHttpRequest (): New window. ActiveXObject ("MSXML2.") XMLHTTP ");
}
function showprocess () {
http = createxmlhttp ();
Http.open ("Get", "<%=request.url.tostring ()%>?step=" + (count++) + "&guid=" + GUID + "&" + date.parse (new
Date ()), true);
Http.setrequestheader ("Connection", "close");
Http.onreadystatechange = function () {
if (http.readystate = = 4 && http.status = 200)
if ("OK" = = Http.responsetext) {
document.getElementById ("process"). InnerHTML = document.getElementById ("Processbar1"). InnerHTML = "complete";
document.getElementById ("Processbar2"). Style.width = "100%";
Window.clearinterval (timer);
}
else {
document.getElementById ("process"). InnerHTML = document.getElementById ("Processbar1"). InnerHTML =
Http.responsetext + "%";
document.getElementById ("Processbar2"). Style.width = Http.responsetext + "%";
}
}
Http.send (NULL);
}
function StartTask () {
Count = 1;
document.getElementById ("process"). InnerHTML = document.getElementById ("Processbar1"). InnerHTML = "0%";
document.getElementById ("Processbar2"). Style.width = "0%";
Timer = Window.setinterval ("showprocess ()", 1000);
return false;
}
</script>
<body>
<form id= "Form1" runat= "Server" >
<input type= "button" value= "Start processing long time operation" onclick= "return StartTask ();"/>
<div style= "border:1px solid blue; width:600px; position:relative;margin:10px 0; " >
<div style= "background: #f00; width:0; height:20px "id=" Processbar2 "></div>
<div style= "Position:absolute; Text-align:center; top:0; width:100% "id=" Processbar1 "></div>
</div>
<div id= "Process" ></div>
</form>
</body>
Code Execution Effect:
But is that the way to do it? Completely wrong, this method still has the phenomenon of inaccurate display, causing inaccurate display is the use of Cache, after IIS 6, increased the function of the application pool, this feature can greatly improve the performance of the program, reduce the program itself caused by the error of the entire site crash. However, if the application pool's "performance"-"Web Garden" number is set to be greater than 1, httpapplicationstate (application), Cache, HttpSessionState (session) These variables are all unusable because: each Web The park will start a w3wp.exe worker process, each of which is independent of each other, and these variables are not shared, so the method of executing progress using the cache save program is not entirely correct.
So what is the ultimate method? Yes, it is possible to keep program execution progress on third party storage media, such as databases, file systems, and so on. This method code I will not write, is to increase access to the database section.