上面方法优点在于session保存的线程运算类对象页面刷新后方便获得运算对象
而用Session["work"]=w可能因为很多原因而丢失
用window.setTimeout('location.href=location.href',1000)刷新,但在页面元素多的情况下页面不断刷新很有可能进度条一直不能显示
下面是在上面的基础上去掉了用session保存线程类而是用在线程类中用静态变量保存当前任务量百分比此方法将带来线程同步问题、使用Ajax实现进度条局部刷新
效果如下面:
前台用Timer控件实时局部刷新。
- <head runat="server">
- <title></title>
- <style type="text/css">
- .lblTxtCenter
- {
- text-align: center;
- }
- </style>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:ScriptManager ID="ScriptManager1" runat="server">
- </asp:ScriptManager>
- <asp:UpdatePanel ID="UpdatePanel1" runat="server">
- <ContentTemplate>
- <div style='width: 200px; background-color: Silver; height: 20px;'>
- <asp:Label runat="server" ID="lbl" CssClass="lblTxtCenter"></asp:Label></div>
- <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick" Enabled="false">
- </asp:Timer>
- <br />
- <asp:Button ID="Button1" runat="server" Text="开始运算" OnClick="Button1_Click" />
- </ContentTemplate>
- </asp:UpdatePanel>
- </div>
- </form>
- </body>
- 后台代码
- protected void Button1_Click(object sender,EventArgs e)
- {
- //线程计算类
- ThreadClass cl = new ThreadClass();
- cl.begin();
- Timer1.Enabled = true;
- }
- protected void Timer1_Tick(object sender,EventArgs e)
- {
- if (ThreadClass.present <= 100)
- {
- Button1.Enabled = false;
- lbl.Text = ThreadClass.present.ToString() + "%";
- lbl.BackColor = System.Drawing.Color.Red;
- lbl.Width = ThreadClass.present * 2;
- }
- if (ThreadClass.present == 100)
- {
- ThreadClass.present = 0;
- Button1.Enabled = true;
- Timer1.Enabled = false;
- }
- }
- 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 }