顯示匯入或上傳的進度,想必是許多 asp.net 開發人員一定會遇到的問題。
以下是我的解法。
為了讓 progress bar 能跑,當然需要 jQuery.
而 JQuery Progress Bar 1.1 已經幫我們寫好了,我們只需要使用即可。
再來,為了讓網頁能立刻反應當下的進度,需要使用 ASP.NET Ajax 的 AJAX 之 PageMethod 功能。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Services;
using System.Web.Services;
using System.Threading;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
private static SlowTask slowTask = null;
protected void Page_Load(object sender, EventArgs e)
{
}
[ScriptMethod]
[WebMethod]
public static Progress GetTaskCurrentProgress()
{
int ii = Thread.CurrentThread.ManagedThreadId;
return new Progress
{
CurrentCount = slowTask.CurrentCount,
TotalCount = slowTask.TotalCount,
Message = string.Format("{0}/{1} : {2}", slowTask.CurrentCount, slowTask.TotalCount,
slowTask.GetAsyncTaskProgress())
};
}
public struct Progress
{
public string Message;
public int TotalCount;
public int CurrentCount;
}
[ScriptMethod]
[WebMethod]
public static void RunItSync()
{
int ii = Thread.CurrentThread.ManagedThreadId;
slowTask = new SlowTask(1000);
slowTask.ExecuteAsyncTask();
}
}
}
Code behinds
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Services;
using System.Web.Services;
using System.Threading;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
private static SlowTask slowTask = null;
protected void Page_Load(object sender, EventArgs e)
{
}
[ScriptMethod]
[WebMethod]
public static Progress GetTaskCurrentProgress()
{
int ii = Thread.CurrentThread.ManagedThreadId;
return new Progress
{
CurrentCount = slowTask.CurrentCount,
TotalCount = slowTask.TotalCount,
Message = string.Format("{0}/{1} : {2}", slowTask.CurrentCount, slowTask.TotalCount,
slowTask.GetAsyncTaskProgress())
};
}
public struct Progress
{
public string Message;
public int TotalCount;
public int CurrentCount;
}
[ScriptMethod]
[WebMethod]
public static void RunItSync()
{
int ii = Thread.CurrentThread.ManagedThreadId;
slowTask = new SlowTask(1000);
slowTask.ExecuteAsyncTask();
}
}
}
sample code download here.
2 則留言:
感謝您的分享
這是我一直想要學習的功能
另外想請問一下,是不是用static的方式
(private static SlowTask slowTask)
如果開啟兩個視窗執行的話
彼此會互相影響?
thx
對不起,一直沒看到這裡的意見。
您的憂慮是對的。此處的 demo 只是簡單的範例。如果要考慮多執行縮時,應該對這個地方再加以變化。例如改儲存到 static List<SlowTask>' slowTasks
張貼留言