It is advisable to start a new thread that will perform the
task, allowing the first thread to return in the thread pool and stand-by to
serve a new incoming request.
To reach our goal, no modifications are required to the actual
codebase that is in charge to execute the task. In the second option we are
going to use a Page's method that first registers an async task, passing three
different event handlers: one to begin/launch the task, one to manage its
completion and the last one used to recover from a timeout that may occur
during the task execution.
This option also uses IAsyncResult
interface described here, but no extra coding is needed to use it, take a look
to the code sample.
The SimpleWorker class exposes one
method that simulates a long running operation, but it only writes a text line
into a log file and waits one second per each line. Imagine an order's
fulfillment procedure that creates packing lists and sends an email to
customers indicating that their orders are "approved."
Listing 1 - Using PageAsyncTask
PageAsyncTask task = new PageAsyncTask(OnBegin, OnEnd, OnTimeout, null);
Page.RegisterAsyncTask(task);
TraceStatusInfo("TEST CASE #2: Start a long running task asynchronously using
PageAsyncTask.");
//Setting up a 5 secs timeout
Page.AsyncTimeout = new TimeSpan(0, 0, 5);
TraceStatusInfo("Starting task");
Page.ExecuteRegisteredAsyncTasks();
If such a procedure is started from an ASP.NET page, it is a
good practice to maintain an activity registry or log
because the web application could be suddenly stopped without any warning and
the worker process may be recycled due to excessive and unexpected resource
consumption.