Ajax实现无刷新任务进度条

前段时间参考了别人写的一篇关于在服务器端用session保存状态,客户端用js实时刷新页面的方法获取后台线程运行的当前任务量百分比如下图:

Ajax实现无刷新任务进度条

上面方法优点在于session保存的线程运算类对象页面刷新后方便获得运算对象

而用Session["work"]=w可能因为很多原因而丢失

用window.setTimeout('location.href=location.href',1000)刷新,但在页面元素多的情况下页面不断刷新很有可能进度条一直不能显示

 

下面是在上面的基础上去掉了用session保存线程类而是用在线程类中用静态变量保存当前任务量百分比此方法将带来线程同步问题、使用Ajax实现进度条局部刷新

效果如下面:

 前台用Timer控件实时局部刷新。

前台代码
   
     
1 < head runat = " server " >
2 < title ></ title >
3 < style type = " text/css " >
4 .lblTxtCenter
5 {
6 text - align: center;
7 }
8 </ style >
9   </ head >
10   < body >
11 < form id = " form1 " runat = " server " >
12 < div >
1
3 < asp:ScriptManager ID = " ScriptManager1 " runat = " server " >
14 </ asp:ScriptManager >
15 < asp:UpdatePanel ID = " UpdatePanel1 " runat = " server " >
16 < ContentTemplate >
17 < div style = ' width: 200px; background-color: Silver; height: 20px; ' >
18 < asp:Label runat = " server " ID = " lbl " CssClass = " lblTxtCenter " ></ asp:Label ></ div >
19 < asp:Timer ID = " Timer1 " runat = " server " Interval = " 1000 " OnTick = " Timer1_Tick " Enabled = " false " >
20 </ asp:Timer >
21 < br />
22 < asp:Button ID = " Button1 " runat = " server " Text = " 开始运算 " OnClick = " Button1_Click " />
23 </ ContentTemplate >
24 </ asp:UpdatePanel >
25 </ div >
26 </ form >
27   </ body >

 

 

后台代码
   
     
1 protected void Button1_Click( object sender, EventArgs e)
2 {
3 // 线程计算类
4   ThreadClass cl = new ThreadClass();
5 cl.begin();
6 Timer1.Enabled = true ;
7 }
8 protected void Timer1_Tick( object sender, EventArgs e)
9 {
10
11 if (ThreadClass.present <= 100 )
12 {
13 Button1.Enabled = false ;
14 lbl.Text = ThreadClass.present.ToString() + " % " ;
15 lbl.BackColor = System.Drawing.Color.Red;
16 lbl.Width = ThreadClass.present * 2 ;
17 }
18 if (ThreadClass.present == 100 )
19 {
20 ThreadClass.present = 0 ;
21 Button1.Enabled = true ;
22 Timer1.Enabled = false ;
23 }
24 }

 

 

线程类
   
     
1 public class ThreadClass
2 {
3 public static int present;
4 public ThreadClass()
5 {
6
7 }
8 public void begin()
9 {
10 if (present == 0 )
11 {
12 lock ( this )
13 {
14 Thread tr = new Thread( new ThreadStart(() =>
15 {
16 for ( int i = 0 ; i <= 1000 ; i ++ )
17 {
18 present = 100 * i / 1000 ; // 计算已完成的百分比
19   Thread.Sleep( 10 );
20 }
21 }));
22 tr.IsBackground = true ;
23 tr.Start();
24 }
25 }
26 }
27 }

 

 

 

你可能感兴趣的:(Ajax)