您的位置:首页 > 编程语言 > ASP

asp.net利用多线程执行长时间的任务,客户端显示出任务的执行进度的示例(一)、(二)

2010-11-25 11:08 585 查看
此方法是在网上找的,不过实施起来会造成页面刷新,不过可以移植到一般处理程序里面,用webservers控制。

代码就不贴了,项目中太多摘不出来。可以自己尝试一下

在asp.net中执行一个长时间的操作,有的时候需要在在客户端有一个反馈能了解到任务的执行进度,大致看了一下有这么几种做法:
(1)按下按钮的时候给出一个<div>提示正在执行任务,执行完毕让这个<div>隐藏
(2)按下按钮的时候跳转到一个提示任务正在执行的页面,执行完毕了再跳转回来
(3)做一个任务类,开启另外一个线程执行任务,同时在客户端或者服务器端保存这个类的实例来跟踪任务的执行情况

(1)和(2)的情况用的比较多,也比较简单,缺点是不能实时的知道任务的执行进度,而且时间一长可能会超时,(3)的方法就会比较好的解决上面说的2个缺点。下面着重说一下(3)的实现方法,先从简单开始,我们做一个任务类,在客户端时时(暂且刷新时间为1秒)得知任务执行了多少时间,并且在成功完成任务后给出执行时间,在任务出错的时候给出出错的时间。

前台

<form id="Form1" method="post" runat="server">
<asp:label id="lab_state" runat="server"></asp:label><br>
<asp:Button id="btn_startwork" runat="server" Text="运行一个长时间的任务"></asp:Button>
</form>

后台

先是一些类的申明:
protected System.Web.UI.WebControls.Button btn_startwork;
protected System.Web.UI.WebControls.Label lab_state;
//前面2个是vs.net自己生成的
protected work w;

在Page_Load里面输入以下代码:

if(Session["work"]==null)
{
w=new work();
Session["work"]=w;
}
else
{
w=(work)Session["work"];
}
switch(w.State)
{
case 0:
{
this.lab_state.Text="还没有开始任务";
break;
}
case 1:
{
this.lab_state.Text="任务进行了"+((TimeSpan)(DateTime.Now-w.StartTime)).TotalSeconds+"秒";
this.btn_startwork.Enabled=false;
Page.RegisterStartupScript("","<script>window.setTimeout('location.href=location.href',1000);</script>");
//不断的刷新本页面,随时更新任务的状态
break;
}
case 2:
{
this.lab_state.Text="任务结束,并且成功执行所有操作,用时"+((TimeSpan)(w.FinishTime-w.StartTime)).TotalSeconds+"秒";
this.btn_startwork.Enabled=true;
break;
}
case 3:
{
this.lab_state.Text="任务结束,在"+((TimeSpan)(w.ErrorTime-w.StartTime)).TotalSeconds+"秒的时候发生错误导致任务失败";
this.btn_startwork.Enabled=true;
break;
}
}

在按钮单击事件内输入以下代码:

if(w.State!=1)
{
this.btn_startwork.Enabled=false;
w.runwork();
Page.RegisterStartupScript("","<script>location.href=location.href;</script>");
//立即刷新页面
}

另外建立一个任务类,代码如下:

public class work
{
public int State=0;//0-没有开始,1-正在运行,2-成功结束,3-失败结束
public DateTime StartTime;
public DateTime FinishTime;
public DateTime ErrorTime;

public void runwork()
{
lock(this)//确保临界区被一个Thread所占用
{
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
{
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlCommand cmd=new SqlCommand("Insert Into test (test)values('test')",conn);
conn.Open();
for(int i=0;i<5000;i++)cmd.ExecuteNonQuery();
conn.Close();
//以上代码执行一个比较消耗时间的数据库操作
State=2;
}
catch
{
ErrorTime=DateTime.Now;
State=3;
}
finally
{
FinishTime=DateTime.Now;
}
}
}
}

运行这个页面,看到每秒页面刷新一次反馈任务执行到现在的时间,在结束后给出任务总的用时。(如果任务出错也给出出错时间)

(这个示例比较简单,基本能实现长时间的任务执行与客户端的交互,但是界面不是很友善,而且如果有很多项操作的话,只能给出执行了多少时间,不能显示执行到第几项任务,在下一篇文章中,将会改进这个类和界面)

对上一次的做一点修改,增加一个比较美观的进度显示



上面那个是运行中的画面,下面那个是结束后的画面



用到的图标在这里:


对上次的前台修改如下:

<%@ Page language="c#" Codebehind="WebForm54.aspx.cs" AutoEventWireup="false" Inherits="csdn.WebForm54" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm54</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<style type="text/css">
.font { FONT-WEIGHT: normal; FONT-SIZE: 9pt; COLOR: #000000; FONT-FAMILY: "宋体", sans-serif; BACKGROUND-COLOR: #f0f0f0; TEXT-DECORATION: none }
</style>
</HEAD>
<body>
<form id="Form1" method="post" 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="请等待" src="clocks.gif" align="left">
<BR>
<asp:Label id="lab_state" runat="server"></asp:Label></P>
</TD>
</TR>
</table>
<BR>
</div>
<asp:Button id="btn_startwork" runat="server" Text="运行一个长时间的任务"></asp:Button><BR>
<BR>
<asp:Label id="lab_jg" runat="server"></asp:Label>
</form>
</body>
</HTML>

后台修改如下:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace csdn
{
/// <summary>
/// WebForm54 的摘要说明。
/// </summary>
public class WebForm54 : System.Web.UI.Page
{
protected System.Web.UI.HtmlControls.HtmlGenericControl div_load;
protected System.Web.UI.WebControls.Button btn_startwork;
protected System.Web.UI.WebControls.Label lab_state;
protected System.Web.UI.WebControls.Label lab_jg;
protected work w;

private void Page_Load(object sender, System.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.lab_state.Text=""+((TimeSpan)(DateTime.Now-w.StartTime)).TotalSeconds.ToString("0.00")+" 秒过去了,完成百分比:"+w.Percent+" %";
this.btn_startwork.Enabled=false;
Page.RegisterStartupScript("","<script>window.setTimeout('location.href=location.href',1000);</script>");
this.lab_jg.Text="";
break;
}
case 2:
{
this.lab_jg.Text="任务结束,并且成功执行所有操作,用时 "+((TimeSpan)(w.FinishTime-w.StartTime)).TotalSeconds+" 秒";
this.btn_startwork.Enabled=true;
this.div_load.Visible=false;
break;
}
case 3:
{
this.lab_jg.Text="任务结束,在"+((TimeSpan)(w.ErrorTime-w.StartTime)).TotalSeconds+"秒的时候发生错误导致任务失败'";
this.btn_startwork.Enabled=true;
this.div_load.Visible=false;
break;
}
}
}

#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btn_startwork.Click += new System.EventHandler(this.btn_startwork_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void btn_startwork_Click(object sender, System.EventArgs e)
{
if(w.State!=1)
{
this.btn_startwork.Enabled=false;
this.div_load.Visible=true;
w.runwork();
Page.RegisterStartupScript("","<script>location.href=location.href;</script>");

}
}
}

public class work
{
public int State=0;//0-没有开始,1-正在运行,2-成功结束,3-失败结束
public int Percent=0;//完成百分比
public DateTime StartTime;
public DateTime FinishTime;
public DateTime ErrorTime;

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
{
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlCommand cmd=new SqlCommand("Insert Into test (test)values('test')",conn);
conn.Open();
for(int p=0;p<100;p++)
{
for(int i=0;i<10;i++)
{
cmd.ExecuteNonQuery();
}
Percent=p;//这里就是定义百分比,你估计这个操作费多少时间定义多少百分比
}
conn.Close();
//以上代码执行一个比较消耗时间的数据库操作
State=2;
}
catch
{
ErrorTime=DateTime.Now;
Percent=0;
State=3;
}
finally
{
FinishTime=DateTime.Now;
Percent=0;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐