asp.net利用多线程执行长时间的任务,客户端显示出任务的执行进度的示例(一)__教程 |
|
日期:2007-5-20 0:39:22 人气:58 [大 中 小] |
|
|
|
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; } } } } 运行这个页面,看到每秒页面刷新一次反馈任务执行到现在的时间,在结束后给出任务总的用时。(如果任务出错也给出出错时间) (这个示例比较简单,基本能实现长时间的任务执行与客户端的交互,但是界面不是很友善,而且如果有很多项操作的话,只能给出执行了多少时间,不能显示执行到第几项任务,在下一篇文章中,将会改进这个类和界面) |
|
出处:本站原创 作者:佚名 |
|
|