Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackgroundWorker thread in ASP.NET

Tags:

Is it possible to use BackGroundWorker thread in ASP.NET 2.0 for the following scenario, so that the user at the browser's end does not have to wait for long time?

Scenario

  1. The browser requests a page, say SendEmails.aspx
  2. SendEmails.aspx page creates a BackgroundWorker thread, and supplies the thread with enough context to create and send emails.
  3. The browser receives the response from the ComposeAndSendEmails.aspx, saying that emails are being sent.
  4. Meanwhile, the background thread is engaged in a process of creating and sending emails which could take some considerable time to complete.

My main concern is about keeping the BackgroundWorker thread running, trying to send, say 50 emails while the ASP.NET workerprocess threadpool thread is long gone.

like image 730
kudlur Avatar asked Sep 11 '08 22:09

kudlur


2 Answers

If you don't want to use the AJAX libraries, or the e-mail processing is REALLY long and would timeout a standard AJAX request, you can use an AsynchronousPostBack method that was the "old hack" in the .net 1.1 days.

Essentially what you do is have your submit button begin the e-mail processing in an asynchronous state, while the user is taken to an intermediate page. The benefit to this is that you can have your intermediate page refresh as much as needed, without worrying about hitting the standard timeouts.

When your background process is complete, it will put a little "done" flag in the database/application variable/whatever. When your intermediate page does a refresh of itself, it detects this flag and automatically redirects the user to the "done" page.

Again, AJAX makes all of this moot, but if for some reason you have a very intensive or timely process that has to be done over the web, this solution will work for you. I found a nice tutorial on it here and there are plenty more out there.

I had to use a process like this when we were working on a "web check-in" type application that was interfacing with a third party application and their import API was hideously slow.

EDIT: GAH! Curse you Guzlar and your god-like typing abilities 8^D.

like image 199
Dillie-O Avatar answered Sep 27 '22 20:09

Dillie-O


You shouldn't do any threading from ASP.NET pages. Any thread that is long running is in danger of being killed when the worker process recycles. You can't predict when this will happen. Any long-running processes need to be handled by a windows service. You can kick off these processes by dropping a message in MSMQ, for example.

like image 23
Eric Z Beard Avatar answered Sep 27 '22 21:09

Eric Z Beard