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

來源:互聯網
上載者:User

下面就是採用靜態變數的方法實現的: 複製代碼 代碼如下:<%@ 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儲存程式執行進度的方法也是不完全正確的。

那麼終極的方法是什麼呢?對,將程式執行進度儲存在第三方的儲存介質上,如資料庫,檔案系統等等都是可以的。這個方法代碼我就不寫了,就是增加訪問資料庫的部分即可。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.