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)