views:

140

answers:

3

Hi,

Quick question. Just want to confirm that a network call such as to a SMTP server doesn't take up any CPU usage. It only blocks one of my request handling threads and the user who triggered the email has to wait while my webserver is done with the SMTP call. If i send the email in another thread and let the user thread go on, then I get rid of this problem. Right???

One colleague of mine suggested using a separate custom web service that would send an email using a smtp server?

A: 

Your theory appears sound. The thread sending the email should spend most of its time just waiting for a response or waiting for an operation to complete, which is not CPU intensive, and should not hog CPU from other threads.

Calling a separate custom web service sounds a bit like unnecessary overhead to me. A SMTP server itself can be called remotely; calling a custom web service instead just adds another layer. But I may have misunderstood your colleague's idea.

thomasrutter
+3  A: 

I would recommend queuing the email, which is then sent via a separate process (either a service or a worker thread). Its a bit more effort to implement initially, but pays off in the long run.

Email servers can go offline, or be slow, so forcing the user to wait may give them a bad experience with your application.

If, for example, you're sending a signup verification email, you might also need to send additional email later if they haven't verified for some period, say 1 day. This becomes easier with the infrastructure supporting a queued design.

devstuff
+1  A: 

I think your best approach is simply to use the SendAsync method of the SmtpClient class to asynchronously send the email.

For example:

SmtpClient client = new SmtpClient(mySMTPHost);
client.SendAsync(myMailMessage, null);

You can even pass in a delegate as the second parameter to the SendAsync method which will act as a callback, and be invoked when the SendAsync method completes. Please see the example on the MSDN site here.

This should give you the best of both worlds in that you can send the email asynchronously without tying up your main executing thread, whilst also avoiding the complexities of spawning and managing your own threads (or writing a separate "service").

CraigTP