Ajax实现无刷新任务进度条

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

上面方法优点在于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 }

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值