Andrew Neely
Andrew Neely

Reputation: 908

Solve a Timeout Error caused by slow email

The Problem

I have a web service that saves a record in the database and, sometimes send out notification emails to a group of users letting them know an event occurred.

I am getting infrequent time-out errors from the client. Since the data are committed to the database, I think my problem is that sending the SMTP server sending the emails is taking longer than the timeout on the client.

The Need

What I am need to do is to send the email either in the background or add it to some sort of queue for sending later and return.

Constraints

Ideas

I've looked at several solutions, but need some direction as to which way would be best.

  1. I could spawn a thread to send the emails, but I don't know if that would work, since the web service code would fall out of scope upon return.
  2. I could add the task to some sort of queue, and periodically send queued emails.
  3. increase the timeout on the client side and ignore the problem.

Under #2, I've looked at Jeff Atwood's use of the HttpRuntime.Cache to simulate a windows service but am very concerned with the warning

You need to really be careful on the length of the task running. Every new Task is a new Worker Thread and there’s a limited number of those – as it “borrows” a thread from the managed thread pool.

An unresponsive web page is worse than the error I'm trying to solve.

What direction should I go?

The Web Service Code

[WebMethod(CacheDuration = 0)]
        public static string SaveRecord(comRecord record, IList<QIData> qiItems)
        {
          using (WebDatabase db = new WebDatabase())
          {
               db.SaveRecord(record, qiItems, UserId, ComId);
                   if (qiItems.Count>0)
               {
                /*Then somehow invoke or queue the routine 
                  db.SendQINotice(record,UserId, (int)ComId));
                 */
               }
           }
        }

Upvotes: 0

Views: 152

Answers (1)

gerrycox
gerrycox

Reputation: 36

Interesting - there are several ways to do it, but since you are on a web site, I would add an entry to an e-mail queue in a database and have another task send out the e-mail. Then you have the freedom to do some better error handling on the e-mail send if you need to without slowing down the web site. For instance, you could add some "transient" error handling to such an application. If you are interested in this approach, I can add to my response the "transient" error handler that I am using to retry on an exception to overcome some temporary error conditions.

Upvotes: 1

Related Questions