asp.net利用多线程执行长时间的任务,客户端显示出任务的执行进度的示例(二)
2007-12-15 09:32:04 来源:WEB开发网核心提示:Page.RegisterStartupScript("","<script>location.href=location.href;</script>"); }} } public class work {pub
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;
}
}
}
}
更多精彩
赞助商链接