ASP. NET tutorial series: Multi-Thread Programming Practice (1)

Source: Internet
Author: User

Multithreading in Web development can enhance user experience, especially when multiple users, multitasking, massive data, and resources are insufficient. So ourASP. NET tutorialSet upSpecial topics on multi-thread programming. The followingCodeThe examples are all entry-level, hoping to help you learn ASP. NET multi-threaded programming.

 

I. ASP. NET uses multithreading for long-time tasks

  

Here we will use a simple example as the starting topic of the practical multi-Thread Programming Tutorial in ASP. NET.

 

When performing a long operation in Asp.net, you may need to have a feedback on the progress of the task on the client. You can roughly see the following methods:
(1) When you press the button, a <div> prompt is displayed indicating that the task is being executed. After the execution is completed, the <div> hidden
(2) When you press the button, you will be redirected to a page indicating that the task is being executed. After the task is executed, you will be redirected back.
(3) create a task class, enable another thread to execute the task, and save the instance of this class on the client or server to track the execution of the task.

(1) and (2) are often used and relatively simple. The disadvantage is that the task execution progress cannot be known in real time, and a long time may time out. (3) the above two shortcomings will be better solved. Next we will focus on the implementation method (3). First, we will create a task class to learn how much time the task has been executed on the client from time to time (the refresh time is 1 second, the execution time is displayed after the task is successfully completed, and the error time is displayed when the task fails.

Front-end

<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 = "running a long task"> </ASP: button>
</Form>

Background

First, some class declarations:
Protected system. Web. UI. webcontrols. Button btn_startwork;
Protected system. Web. UI. webcontrols. Label lab_state;
// The first two are self-generated by vs.net.
Protected work W;

Enter the following code in 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 = "task not started ";
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 and update the task status at any time
Break;
}
Case 2:
{
This. lab_state.text = "the task is finished and all operations are successfully performed, with" + (timespan) (W. FinishTime-w.StartTime). totalseconds + "seconds ";
This. btn_startwork.enabled = true;
Break;
}
Case 3:
{
This. lab_state.text = "task ended, with an error in" + (timespan) (W. ErrorTime-w.StartTime). totalseconds + "seconds leading to task failure ";
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 the page immediately
}

Create a task class with the following code:

Public class work
{
Public int state = 0; // 0-not started, 1-running, 2-successful, 3-failed
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. deleettings ["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 ();
// Execute a time-consuming database operation with the above Code
State = 2;
}
Catch
{
Errortime = datetime. now;
State = 3;
}
Finally
{
Finishtime = datetime. now;
}
}
}
}

Run this page and you will see the time when the feedback task is executed every second. The total time of the task is given after the end. (If a task error occurs, the error time is also displayed)

(This example is relatively simple. It can basically implement the interaction between long-time task execution and the client, but the interface is not very friendly. If there are many operations, you can only give the execution time, the number of tasks to be executed cannot be displayed.Article<ASP. NET tutorial series: multi-threaded programming (I) Continued> http://www.cnblogs.com/elock/archive/2010/04/11/1709566.html, this class and interface will be added)

 

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.