asp.net多线程,执行真实时间与百分比的进度条

asp.net利用多线程执行长时间的任务,客户端显示任务执行的真实时间与百分比。

在asp.net中执行一个长时间的操作,有的时候需要在在客户端有一个反馈能了解到任务的执行进度,大致看了一下有这么几种做法:
(1)按下按钮的时候给出一个<div>提示正在执行任务,执行完毕让这个<div>隐藏
(2)按下按钮的时候跳转到一个提示任务正在执行的页面,执行完毕了再跳转回来
(3)做一个任务类,开启另外一个线程执行任务,同时在客户端或者服务器端保存这个类的实例来跟踪任务的执行情况
(1)和(2)的情况用的比较多,也比较简单,缺点是不能实时的知道任务的执行进度,而且时间一长可能会超时,(3)的方法就会比较好的解决上面说的2个缺点。下面着重说一下(3)的实现方法,先从简单开始,我们做一个任务类,在客户端时时(暂且刷新时间为1秒)得知任务执行了多少时间,并且在成功完成任务后给出执行时间,在任务出错的时候给出出错的时间。 

前台调用代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>asp.net利用多线程执行长时间的任务,客户端显示任务的执行进度的示例</title>
    <style type="text/css">
        .font{ font-size:9pt; color:#000000; background-color:#f0f0f0; text-decoration:none;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div id="div_load" runat="server">
        <table width="320" height="72" border="1" bordercolor="#cccccc" cellpadding="5" cellspacing="1" class="font" style="filter: Alpha(opacity=80); width: 320px; height: 72px">
            <tr><td><p><img alt="请等待" align="left" src="load.gif" /><br />
                <asp:Label ID="labState" runat="server"></asp:Label></p></td></tr>
        </table>
        <br />
    </div>
    <asp:Button ID="BtnLong" runat="server" Text="运行一个长时间的任务" 
        οnclick="BtnLong_Click" /><br />
    <asp:Label ID="labJg" runat="server"></asp:Label>
    </form>
</body>
</html>


后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    Work w;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["work"] == null)
        {
            w = new Work();
            Session["work"] = w;
        }
        else
        {
            w = (Work)Session["work"];
        }
        
        switch (w.state)
        {
            case 0:
                this.div_load.Visible = false;
                break;
            case 1:
                this.labState.Text = (DateTime.Now - w.startTime).TotalSeconds.ToString("0.00") + "秒过去了,完成百分比:" + w.percent + "%";
                this.BtnLong.Enabled = false;
                this.Page.RegisterStartupScript("", "<script>window.setTimeout('location.href=location.href',1000);</script>");
                this.labJg.Text = "";
                break;
            case 2:
                this.labJg.Text = "任务结束,并且成功执行所有操作,用时 " + (w.finishTime - w.startTime).TotalSeconds + " 秒";
                this.BtnLong.Enabled = true;
                this.div_load.Visible = false;
                break;
            case 3:
                this.labJg.Text = "任务结束,在" + (w.errorTime - w.startTime).TotalSeconds + "秒的时候发生错误导致任务失败";
                this.BtnLong.Enabled = true;
                this.div_load.Visible = false;
                break;
        }
    }
    protected void BtnLong_Click(object sender, EventArgs e)
    {
        if (w.state != 1)
        {
            this.BtnLong.Enabled = false;
            this.div_load.Visible = true;
            w.RunWork();
            this.Page.RegisterStartupScript("", "<script>window.location.href=location.href;</script>");
        }
    }
}


Work类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
///Work 的摘要说明
/// </summary>
public class Work
{
    /// <summary>
    /// 0没有开始,1正在运行,2成功结束,3失败结束
    /// </summary>
    public int state = 0;

    /// <summary>
    /// 完成百分比
    /// </summary>
    public int percent = 0;

    public DateTime startTime;
    public DateTime finishTime;
    public DateTime errorTime;

	public Work()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}

    public void RunWork()
    {
        lock (this)
        {
            if (state != 1)
            {
                state = 1;
                startTime = DateTime.Now;
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(DoWork));
                thread.Start();
            }
        }
    }

    private void DoWork()
    {
        try
        {
            //System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
            //System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("INSERT INTO STUTINFO(MYNAME,MYAGE,MYNOBER) VALUES('test',30,'ABC')", conn);
            //conn.Open();
            for (int p = 0; p < 100; p++)
            {
                //cmd.ExecuteNonQuery();

                for (int n = 100000000; n > 0; n--)
                { 
                    
                }

                percent = p;
            }
            //conn.Close();
            state = 2;
        }
        catch
        {
            errorTime = DateTime.Now;
            percent = 0;
            state = 3;
        }
        finally
        {
            finishTime = DateTime.Now;
            percent = 0;
        }
    }
}

 

运行效果如下:

 

加载图片:


本案例来源于:http://www.alixixi.com/program/a/2008050627073.shtml

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值