Asp. NET Tutorial Series: Multithreaded Programming Combat (i)

Source: Internet
Author: User

Using multithreading in Web development can enhance the user experience, especially in the case of multi-user, multitasking, massive data, and resource constraints. So our ASP. NET tutorial set up multi-threaded programming practical topics . The following code examples are all entry-level and hope to be helpful to you in learning ASP.

An ASP. NET uses multithreading to perform long-time tasks

Here is a simple example of the beginning of our ASP. NET tutorial multi-threaded programming combat topic.

A long operation is performed in ASP. Sometimes it is necessary to have a feedback on the client to understand the progress of the task, and to take a look at some of the following practices:
(1) When the button is pressed to give a <div> prompt is executing the task, the execution is complete let this <div> hide
(2) Press the button to jump to a prompt task is executing the page, the execution is finished and then jump back
(3) Do a task class, open another thread to perform the task, while saving instances of this class on the client or server side to track the execution of the task

(1) and (2) The situation with more, but also relatively simple, the disadvantage is not real-time to know the progress of the task, and the time may be timed out, (3) The method will be better to solve the above mentioned 2 shortcomings. The following emphasis on the implementation of (3), starting from the simple, we do a task class, in the client time (the refresh time is 1 seconds) to know how long the task executes, and after the successful completion of the task to give the execution time, when the task is wrong to give the time of the 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, there are some class declarations:
protected System.Web.UI.WebControls.Button btn_startwork;
protected System.Web.UI.WebControls.Label lab_state;
The first 2 are generated by vs.net themselves.
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= "The task has not yet begun";
Break
}
Case 1:
{
This.lab_state. text= "task has been" + (TimeSpan) (Datetime.now-w.starttime)). totalseconds+ "seconds";
This.btn_startwork. Enabled=false;
Page.registerstartupscript ("", "<script>window.settimeout (' Location.href=location.href ',"); </script > ");
Constantly refresh this page, update the status of the task at any time
Break
}
Case 2:
{
This.lab_state. text= "task ends and all operations are performed successfully, time" + (TimeSpan) (W.finishtime-w.starttime)). totalseconds+ "seconds";
This.btn_startwork. Enabled=true;
Break
}
Case 3:
{
This.lab_state. text= "Task end, in" + ((TimeSpan) (W.errortime-w.starttime)). totalseconds+ "Second error causes the task to fail";
This.btn_startwork. Enabled=true;
Break
}
}

Enter the following code within 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
}

Also create a task class with the following code:

public class work
{
public int state=0;//0-not started, 1-running, 2-end successfully, 3-end of failure
Public DateTime StartTime;
Public DateTime Finishtime;
Public DateTime Errortime;

public void Runwork ()
{
Lock (this)//Ensure that the critical section 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" values (' Test ') ", conn);  
    Conn. Open ();  
    for (int i=0;i<5000;i++) cmd. ExecuteNonQuery ();  
    Conn. Close ();  
   //The above code executes a time-consuming database operation  
    state=2; 
   } 
   catch 
   { 
    Errortime=datetime.now;  
    state=3; 
  } 
   finally 
   { 
    finishtime=datetime.now; 
  } 
 } 
 }  
}

Run this page and see the page refresh once per second the feedback task executes to the present time, after the completion of the task total. (Error time if task is wrong)

(This example is relatively simple, the basic can achieve long-term task execution and client interaction, but the interface is not very friendly, and if there are many operations, can only give the amount of time to execute, can not show the execution to the first few tasks, the next article <asp. NET Tutorial Series: Multithreaded Programming Combat (a) Continue >http://www.cnblogs.com/elock/archive/2010/04/11/1709566.html, this class and interface will be improved)

Asp. NET Tutorial Series: Multithreaded Programming Combat (i)

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.