程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.net 在客戶端顯示服務器端任務處理進度條的探討

asp.net 在客戶端顯示服務器端任務處理進度條的探討

編輯:ASP.NET基礎
下面就是采用靜態變量的方法實現的:
復制代碼 代碼如下:
<%@ 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; //設置初始值,防止出現被0除。
protected void ProcessTask()
{
//通過計算,得出TotalCount的值,比如查詢數據庫等
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>

<html xmlns="http://www.w3.org/1999/xhtml ">
<head runat="server">
<title>在客戶端顯示服務器端任務處理進度條的探討</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 = "完成";
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>

</head>
<body>
<form id="form1" runat="server">
<input type="button" value="開始處理長時間操作" onclick="return startTask();" />
<div id="process"></div>
</form>
</body>
</html>

這種方法,在一個用戶訪問的情況下是沒有問題的,但多個用戶訪問時就會造成混亂。

下面這這種方法,是常用的方法,一般情況下可以滿足需求:
復制代碼 代碼如下:
<%@ 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>
/// 設置全局變量,以便不同的方法是用
/// </summary>
private int Processbar = 0; //設置初始的狀態,也可以代表一系列步驟中的每個步驟。
private int TotalCount = 100; //設置初始值,防止出現被0除。
private String key;
protected void ProcessTask()
{
while (Processbar < TotalCount)
{
Processbar = this.GetProcessbar() + 5; //這裡只是模擬一下,每次加 5
System.Threading.Thread.Sleep(1000); //這裡只是模擬一個長時間的執行過程。
SaveData();
}
}

protected void Page_Load(object sender, EventArgs e)
{
key = Request.QueryString["guid"]; //多個並發請求時,用來區分客戶端的請求。
if (String.IsNullOrEmpty(key)) key = Guid.NewGuid().ToString();
Processbar = this.GetProcessbar();
TotalCount = this.GetTotalCount();

//以下判斷原來判斷請求的不同過程,是第一次請求,還是更新進度條的請求,實現方法也可以劃分為多個程序來實現。
if (Request.QueryString["step"] != null && Request.QueryString["step"].Equals(String.Empty) == false)
{
if (Request.QueryString["step"].Equals("1"))
{
// 開始執行任務的請求,啟動長時間的任務處理。
Processbar = 0;
//通過計算,得出TotalCount的值,比如查詢數據庫等,也可以是一個任務的多個步驟的總和。
TotalCount = 200; //假如完成一個任務需要200個步驟
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)
{
// 輸出處理的過程
Response.Write(Processbar * 100 / TotalCount);
}
else
{
// 所有的任務都完成了,輸出結束信息,終止前端的請求。
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>
/// 得到執行過程的階段
/// </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>
/// 得到全部的過程數
/// </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>
/// 將過程保存。
/// </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>

<html xmlns="http://www.w3.org/1999/xhtml ">
<head id="Head1" runat="server">
<title>在客戶端顯示服務器端任務處理進度條的探討</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 = "完成";
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>

</head>
<body>
<form id="form1" runat="server">
<input type="button" value="啟動處理長時間操作" 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>
</html>

代碼執行效果:
孟憲會 
但是,這種方法就是萬事大吉了嗎?完全錯誤,這種方法仍然存在顯示不准確的現象,造成顯示不准確的原因就是 Cache 的使用,IIS 6之後,增加了應用程序池的功能,這個功能可以大大提高程序的性能,減少程序本身的錯誤導致的整個網站的崩潰。但是,如果應用程序池的“性能”-“Web 園”數目設置大於1的情況下,HttpApplicationState(Application)、Cache、HttpSessionState(Session)這些變量都是都是無法使用了,這是因為:每個Web 園會啟動一個w3wp.exe工作進程,每個工作進程之間是相互獨立的,以上這些變量也就是不是共享的了,所以,使用Cache保存程序執行進度的方法也是不完全正確的。

那麼終極的方法是什麼呢?對,將程序執行進度保存在第三方的存儲介質上,如數據庫,文件系統等等都是可以的。這個方法代碼我就不寫了,就是增加訪問數據庫的部分即可。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved