Talking about the task of taking advantage of ASP. NET multithreading for a long time

Source: Internet
Author: User

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 task is executed, hide the <div>

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 task execution 1) and 2) it is also relatively simple. The disadvantage is that you cannot know the progress of the task 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 3) implementation method. First, we will create a task class, which will be refreshed for 1 second at the client time) to learn how long the task has been executed, the execution time is displayed after the task is successfully completed, and the error time is displayed when the task fails.

ASP. NET multi-thread foreground

 
 
  1. <Form Id="Form1" Method="Post" Runat="Server">
  2. <Asp: label Id="Lab_state" Runat="Server"></Asp: label><Br>
  3. <Asp: Button Id="Btn_startwork" Runat="Server" Text="Running a long task"></Asp: Button>
  4. </Form>

ASP. NET multi-thread background

First, some class declarations:

 
 
  1. Protected System. Web. UI. WebControls. Button btn_startwork;
  2. Protected System. Web. UI. WebControls. Label lab_state;
  3. // The first two are self-generated by vs.net.
  4. Protected work w;
  5. Enter the following code in Page_Load:
  6. If (Session ["work"] = null)
  7. {
  8. W=NewWork ();
  9. Session ["work"] = w;
  10. }
  11. Else
  12. {
  13. W= (Work) Session ["work"];
  14. }
  15. Switch (w. State)
  16. {
  17. Case 0:
  18. {
  19. This. lab_state.Text="Task not started";
  20. Break;
  21. }
  22. Case 1:
  23. {
  24. This. lab_state.Text="The task has been executed"+ (TimeSpan) (DateTime. Now-w.StartTime). TotalSeconds + "seconds ";
  25. This. btn_startwork.Enabled=False;
  26. Page. RegisterStartupScript ("","<Script>Window. setTimeout ('LocationLocation. href= Location. href ', 1000 );</Script>");
  27. // Constantly refresh this page and update the task status at any time
  28. Break;
  29. }
  30. Case 2:
  31. {
  32. This. lab_state.Text="When the task ends and all operations are successfully performed"+ (TimeSpan) (w. FinishTime-w.StartTime). TotalSeconds + "seconds ";
  33. This. btn_startwork.Enabled=True;
  34. Break;
  35. }
  36. Case 3:
  37. {
  38. This. lab_state.Text="The task is finished. In"+ (TimeSpan) (w. ErrorTime-w.StartTime). TotalSeconds + "an error occurs in seconds, causing task failure ";
  39. This. btn_startwork.Enabled=True;
  40. Break;
  41. }
  42. }

Enter the following code in the button-click event:

 
 
  1. If (w. State! = 1)
  2. {
  3. This. btn_startwork.Enabled=False;
  4. W. runwork ();
  5. Page. RegisterStartupScript ("","<Script>LocationLocation. href= Location. href;</Script>");
  6. // Refresh the page immediately
  7. }

Create a task class with the following code:

 
 
  1. Public class work
  2. {
  3. Public intState=0; // 0-no start, 1-running, 2-success, 3-Failure
  4. Public DateTime StartTime;
  5. Public DateTime FinishTime;
  6. Public DateTime ErrorTime;
  7. Public void runwork ()
  8. {
  9. Lock (this) // ensure that the critical section is occupied by a Thread
  10. {
  11. If (State! = 1)
  12. {
  13. State=1;
  14. StartTime=DateTime. Now;
  15. System. Threading. ThreadThread=NewSystem. Threading. Thread (new System. Threading. ThreadStart (dowork ));
  16. Thread. Start ();
  17. }
  18. }
  19. }
  20. Private void dowork ()
  21. {
  22. Try
  23. {
  24. SqlConnectionConn=NewSqlConnection (System. Configuration. ConfigurationSettings. receivettings ["conn"]);
  25. SqlCommandCmd=NewSqlCommand ("Insert Into test (test) values ('test')", conn );
  26. Conn. Open ();
  27. For (intI=0; I<5000; I ++) cmd. ExecuteNonQuery ();
  28. Conn. Close ();
  29. // Execute a time-consuming database operation with the above Code
  30. State=2;
  31. }
  32. Catch
  33. {
  34. ErrorTime=DateTime. Now;
  35. State=3;
  36. }
  37. Finally
  38. {
  39. FinishTime=DateTime. Now;
  40. }
  41. }
  42. }
  43. }

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 ASP. the. NET multi-thread 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, it can only show how long it has been executed, the number of tasks executed cannot be displayed. In the next article, this class and interface will be improved)

  1. DataList and Repeater controls of ASP. NET
  2. Analysis of IIS ing in ASP. NET
  3. Overview ASP. NET status types
  4. Introduction to ASP. NET and Web servers
  5. EnableViewState attribute of ASP. NET

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.