A solution for time-consuming operations in ASP. NET

Source: Internet
Author: User

In ASP. NET, multithreading can be used to achieve the same purpose.
Multithreading

The code is as follows: Copy code

<% @ 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>
<BR>
<Asp: Label id = "lab_state" runat = "server"> </asp: Label> </P>
</TD>
</TR>
</Table>
<BR>
</Div>
<Asp: Button id = "btn_startwork" runat = "server" Text = "running a long task"> </asp: Button> <BR>
<BR>
<Asp: Label id = "lab_jg" runat = "server"> </asp: Label>
</Form>
</Body>
</HTML>

The background modification is as follows:

The code is as follows: Copy code

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 of 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 the 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, completion percentage:" + 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 is finished and all operations are successfully performed, with" + (TimeSpan) (w. FinishTime-w.StartTime). TotalSeconds + "seconds ";
This. btn_startwork.Enabled = true;
This. div_load.Visible = false;
Break;
    }
Case 3:
    {
This. lab_jg.Text = "task ended, with an error in" + (TimeSpan) (w. ErrorTime-w.StartTime). TotalSeconds + "seconds leading to task failure '";
This. btn_startwork.Enabled = true;
This. div_load.Visible = false;
Break;
    }
   }
  }

# Code generated by region Web form designer
Override protected void OnInit (EventArgs e)
  {
//
// CODEGEN: This call is required by the ASP. NET Web form designer.
//
InitializeComponent ();
Base. OnInit (e );
  }
  
/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content 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-not started, 1-running, 2-successful, 3-failed
Public int Percent = 0; // percentage of completion
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. Deleettings ["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; // The percentage is defined here. You can estimate how much time the operation fee is defined as a percentage.
    }
Conn. Close ();
// Execute a time-consuming database operation with the above code
State = 2;
   }
Catch
   {
ErrorTime = DateTime. Now;
Percent = 0;
State = 3;
   }
Finally
   {
FinishTime = DateTime. Now;
Percent = 0;
   }
  }
 }
}

Time-consuming operations in network management are often repetitive operations. For example, to generate a static page, you often need to refresh the page periodically. This type of task is automatically executed by the program to meet our requirements.

Use multithreading in ASP. NET

Code
// Scheduled tasks of the program. Each task implements ISchedulerWork.

Public interface ISchedulerWork
        {
Void Execute ();
        }

// Assessment module -- assessment of personal notification email tasks
Public class EmaiSendingJob: ISchedulerWork
        {
Public void Execute ()
            {
                                ;

            }
        }

// Create a configuration object to store the tasks to be periodically executed and the execution interval.
Public class SchedulerConfiguration
        {
// Execute once every day at intervals
Private int sleepInterval;

// Task list
Private ArrayList jobs = new ArrayList ();


Public int SleepInterval {get {return sleepInterval ;}}
Public ArrayList Jobs {get {return jobs ;}}

// Constructor of the scheduling configuration class
Public SchedulerConfiguration (int newSleepInterval)
            {
SleepInterval = newSleepInterval;
            }
        }

// Scheduling class, scheduled to execute the task of the configuration object
Public class Scheduler
        {
Private SchedulerConfiguration configuration = null;

Public Scheduler (SchedulerConfiguration config)
            {
Configuration = config;
            }

Public void Start ()
            {
While (true)
                {
// Execute each task
Foreach (ISchedulerWork job in configuration. Jobs)
                    {
Thread myThread = new Thread (new ThreadStart (job. Execute ));
MyThread. Start ();
Thread. Sleep (configuration. SleepInterval );
                    }
                }
            }
        }

In global program events:

Code
Protected void Application_Start (object sender, EventArgs e)
        {
SchedulerConfiguration config =
New SchedulerConfiguration (1000*60*60*23 );

Config. Jobs. Add (new. EmailSendingJob ());

Scheduler scheduler = new Scheduler (config );

SchedulerThread = new System. Threading. Thread (new System. Threading. ThreadStart (schedstart. Start ));
SchedulerThread. Start ();


        }

Protected void Application_End (object sender, EventArgs e)
        {
Try
            {
// Destroy the program upon exit
If (schedulerThread! = Null)
                {
SchedulerThread. Abort ();
                }
            }
Catch
            {
// Operation
                ;
            }
        }


To implement the job scheduler function similar to windows. Therefore, zero intervention can be managed.

 

The environment of multi-thread execution tasks in WEB applications is different from that of common asp.net pages. For example, HttpContext in the page cannot be used normally in multi-threaded programs. What should I do if I want to use this object? It is very simple. Since it is an object, you can pass it over.

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.