一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

ASP.NET中执行耗时操作的解决方案

时间:2013-01-05 编辑:简简单单 来源:一聚教程网

在ASP.NET中可以利用多线程方式来达到同样的目的。
多线程

 代码如下 复制代码

<%@ Page language="c#" Codebehind="WebForm54.aspx.cs" AutoEventWireup="false" Inherits="csdn.WebForm54" %>


 
  WebForm54
 
 
 
 
 
 
 
 


  

         class="font" style="FILTER: Alpha(opacity=80); WIDTH: 320px; HEIGHT: 72px">
    
     
    
   

      

请等待
       

       


     

   

  

  

  

  
 

 

后台修改如下:

 代码如下 复制代码

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
{
 ///


 /// WebForm54 的摘要说明。
 ///

 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("","");
     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);
  }
  
  ///


  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  ///

  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("","");
            
   }
  }
 }

 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;
   }
  }
 }
}

网管管理中的耗时操作,往往又是重复性的操作。比如说生成静态页面,往往要周期性的重新生成一遍。这种任务,使用程序自动执行来完成更符合我们的要求。

在ASP.NET中使用多线程结合

代码
//  程序的定期任务,每个任务都实现ISchedulerWork

        public interface ISchedulerWork
        {
            void Execute();
        }

        //考核模块——考核个人通知邮件任务
        public class EmaiSendingJob : ISchedulerWork
        {
            public void Execute()
            {
                                ;

            }
        }

        //建立一个配置对象,用来存储要定期执行的任务和执行的时间间隔。
        public class SchedulerConfiguration
        {
            //时间间隔  每天执行一次
            private int sleepInterval;

            //任务列表
            private ArrayList jobs = new ArrayList();


            public int SleepInterval { get { return sleepInterval; } }
            public ArrayList Jobs { get { return jobs; } }

            //调度配置类的构造函数
            public SchedulerConfiguration(int newSleepInterval)
            {
                sleepInterval = newSleepInterval;
            }
        }

        //调度类,定时执行配置对象的任务
        public class Scheduler
        {
            private SchedulerConfiguration configuration = null;

            public Scheduler(SchedulerConfiguration config)
            {
                configuration = config;
            }

            public void Start()
            {
                while (true)
                {
                    //执行每一个任务
                    foreach (ISchedulerWork job in configuration.Jobs)
                    {
                        Thread myThread = new Thread(new ThreadStart(job.Execute));
                        myThread.Start();
                        Thread.Sleep(configuration.SleepInterval);
                    }
                }
            }
        }

在程序全局事件中:

代码
  protected void Application_Start(object sender, EventArgs e)
        {
            SchedulerConfiguration config =
                new SchedulerConfiguration(1000 * 60 * 60 * 23);

            config.Jobs.Add(new .EmailSendingJob());

            Scheduler scheduler = new Scheduler(config);

            schedulerThread = new System.Threading.Thread(new System.Threading.ThreadStart(scheduler.Start));
            schedulerThread.Start();


        }

  protected void Application_End(object sender, EventArgs e)
        {
            try
            {
                //程序退出时进行销毁
                if (schedulerThread != null)
                {
                    schedulerThread.Abort();
                }
            }
            catch
            {
                //operation
                ;
            }
        }


方法,就能实现类似windows计划任务的功能。从而实现0干预的管理。

 

在WEB应用程序中使用多线程执行任务,其环境跟普通的asp.net页面有一些不同。例如页面中的HttpContext在多线程程序中就不能正常使用。想使用这个对象怎么办呢?很简单,既然是对象,传过去就行了。

热门栏目