ASP.net An example of the progress of a task's execution by using multithreading to perform long tasks

Source: Internet
Author: User
Tags current time datetime execution insert thread visual studio
Asp.net| Multithreading | client | example | show | execute make a little change to the last time, add a more beautiful progress show


The top one is the running picture, the following is the end of the picture

The icons used are here:

Changes to the last front desk are as follows:

<%@ 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: "Song Body", 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= "height=" border= "1" bordercolor= "#cccccc" cellpadding= "5" cellspacing= "1"
class= "Font" style= "Filter:alpha" (opacity=80); width:320px; height:72px ">
<TR>
<TD>
<p>
<BR>
<asp:label id= "lab_state" runat= "Server" ></asp:Label></P>
</TD>
</TR>
</table>
<BR>
</div>
<asp:button id= "btn_startwork" runat= "Server" text= "Run a long time task" ></asp:Button><BR>
<BR>
<asp:label id= "LAB_JG" runat= "Server" ></asp:Label>
</form>
</body>
</HTML>

Background modifications are as follows:

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>
Summary description of the 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)
{
Place user code here to initialize page
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") + "seconds passed, percent complete:" +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= "The task ends and all operations are performed successfully, when" + ((TimeSpan) (W.finishtime-w.starttime)). totalseconds+ "seconds";
This.btn_startwork. Enabled=true;
This.div_load. Visible=false;
Break
}
Case 3:
{
This.lab_jg. Text= "The task ends in" + ((TimeSpan) (W.errortime-w.starttime)). totalseconds+ "Second error causes the task to fail";
This.btn_startwork. Enabled=true;
This.div_load. Visible=false;
Break
}
}
}

Code generated #region the Web forms Designer
Override protected void OnInit (EventArgs e)
{
//
CodeGen: This call is required for the ASP.net Web forms Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
</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-No start, 1-running, 2-Successful end, 3-fail end
public int percent=0;//percent complete
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;//here is the definition of percentage, and you estimate how much time the operating fee defines.
}
Conn. Close ();
The above code performs a database operation that consumes time
state=2;
}
Catch
{
Errortime=datetime.now;
percent=0;
state=3;
}
Finally
{
Finishtime=datetime.now;
percent=0;
}
}
}
}

Perform a long operation in asp.net, and sometimes need to have a feedback on the client to understand the progress of the task, a general look at a number of ways to do this:
(1) When the button is pressed to give a <div> hint is performing a task, execution let this <div> hide
(2) When the button is pressed to jump to a prompt task is executing the page, execution finished and then jump back
(3) Make a task class, open another thread to perform the task, and save an instance of this class on the client or server side to track the execution of the task
(1) and (2) The situation used more, but also relatively simple, the disadvantage is not real-time know the progress of the task, and a long time may be timed out, (3) The method will be better to solve the above mentioned 2 shortcomings. The following is an emphasis on (3) Implementation methods, first from the simple start, we do a task class, at the client time (the refresh time is 1 seconds) to know how long the task has been performed, and after the successful completion of the task to give the execution time, when the task error time to give an error.
Front desk
<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= "Run a long time task" ></asp:Button>
</form>
Background
First, the declarations of some classes:
protected System.Web.UI.WebControls.Button btn_startwork;
protected System.Web.UI.WebControls.Label lab_state;
The first 2 were generated by vs.net.
protected work w;
Enter the following code inside the 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= "has not yet begun the task";
Break
}
Case 1:
{
This.lab_state. text= "task performed" + ((TimeSpan) (Datetime.now-w.starttime)). totalseconds+ "seconds";
This.btn_startwork. Enabled=false;
Page.registerstartupscript ("", "<script>window.settimeout" (' Location.href=location.href ', 1000); </script > ");
Constantly refresh this page, update the status of the task at any time
Break
}
Case 2:
{
This.lab_state. Text= "The task ends and all operations are performed successfully, when" + ((TimeSpan) (W.finishtime-w.starttime)). totalseconds+ "seconds";
This.btn_startwork. Enabled=true;
Break
}
Case 3:
{
This.lab_state. Text= "The task ends in" + ((TimeSpan) (W.errortime-w.starttime)). totalseconds+ "Second error causes the task to fail";
This.btn_startwork. Enabled=true;
Break
}
}
Enter the following code in the button click event:
if (w.state!=1)
{
This.btn_startwork. Enabled=false;
W.runwork ();
Page.registerstartupscript ("", "<script>location.href=location.href;</script>");
Refresh page Now
}

Create a different task class with the following code:
public class work
{
public int state=0;//0-No start, 1-running, 2-Successful end, 3-fail end
Public DateTime StartTime;
Public DateTime Finishtime;
Public DateTime Errortime;
public void Runwork ()
{
Lock (this)//ensures that the critical area is occupied by a 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 ();
The above code performs a database operation that consumes time
state=2;
}
Catch
{
Errortime=datetime.now;
state=3;
}
Finally
{
Finishtime=datetime.now;
}
}
}
}
Run this page, see the page refresh once per second feedback task execution to the current time, at the end of the total given the task. (If the task error also gives an error time)
(This example is relatively simple, the basic ability to implement a long task to perform interaction with the client, but the interface is not very friendly, and if there are many operations, can only give the execution of how much time, can not show the execution to the first few tasks, in the next article, will improve the class and interface.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.