ASP.Net教程系列:多線程編程實戰(一) 續

來源:互聯網
上載者:User

本文是ASP.Net教程多線程編程實戰專題一的續文,對ASP.Net利用多線程執行長時間的任務的範例中會多線程類及介面的改進。希望編程愛好者能提出寶貴意見。

 

對上一次的做一點修改,增加一個比較美觀的進度顯示


上面那個是運行中的畫面,下面那個是結束後的畫面 

 

用到的表徵圖在這裡:

對上次的前台修改如下:

<%@ 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 Form設計器產生的程式碼
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 該調用是 ASP.NET Web Form設計器所必需的。
   //
   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;
   }
  }
 }
}

 

引用地址:http://www.cnblogs.com/lovecherry/archive/2005/04/10/135090.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.