ASP. NET Website background task

Source: Internet
Author: User

Many websites require background tasks, such as regularly sending emails to be sent in the queue or regularly checking applications.Program. This document describes how to implement an ASP. NET Website background task.
First, let's take a look at the application_start function in the global. asax. CS file. When the first user visits the website after the website is startedCodeWill be executed. Here we create a thread to execute background tasks.

1 Thread backgroundthread =   New Thread ( New Threadstart (tasks. Start ));
2 Backgroundthread. Start ();

When this thread is started, we use a timer to regularly execute the task.

1 Timer t =   New Timer ( 10000 ); // Run Once every 10 seconds
2 T. elapsed + =   New Elapsedeventhandler (writefile ); // The writefile method is the method for scheduled execution.
3 T. Enabled =   True ;
4 T. autoreset =   True ;

In this example, the scheduled task is to write the current time to a text file.

Streamwriter SW =   New Streamwriter (filepath, True );
Sw. writeline ( " {0} \ n " , Datetime. Now. tostring ());
Sw. Flush ();
Sw. Close ();

In this way, the ASP. NET Website background executes a scheduled task.

 

Download Sample Code (available in Visual Studio 2010)

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.