views:

52

answers:

2

I have a WCF service with many methods. I would like that after executing one of the methods emails will be send to some users. Sending emails may be a long running operation and I don't want a caller of the method to await this time. The caller should receive a response as soon as it is computed and the emails should be send afterwards. I was thinking about sending the emails in a new thread, but I am not sure if it is correct to start new threads when WCF service is hosted in IIS. Could somebody tell me what is the best practice in such cases?

Thanks in advance Lukasz Glaz

A: 

There is nothing inherently problematic about starting new threads when a service is hosted in IIS, but consider this:

How important is it that the email is sent?

When you start a background thread, there is no guarantee that the process doesn't crash before the operation completes. In worst cases, the machine may simply crash due to external reasons (loss of power, Blue Screen of Death, etc.) and there's really nothing you can do to prevent that. In such cases (and perhaps less severe cases as well), the thread may never complete its operation, meaning that the email is never sent.

If you can live with that, sending the email from a new thread is fine.

If, one the other hand, you must guarantee that the email will always be sent, you will need to hand off that operation to a transactional queue of some sort (either MSMQ, a database table or some other transactional mechanism).

In that case, you then need another robust background process (a Windows Service comes to mind) that pulls messages off the queue and sends the emails. This architecture guarantees that the emails will eventually be sent, even if the server suddenly reboots. However, it is a much more complex setup, so I think you should only implement it if the requirements state that emails must be sent.

Mark Seemann
The emails are only an additional notification so there should be no need for a more complex solution.Concerning starting the thread: should I just create a new Thread instance or use a ThreadPool? I may add that the method which requires sending emails is called not very often (a few times per day).
GUZ
Unless you explicitly need a reference to the Thread, the ThreadPool will do nicely - it should be your first choice of starting a new thread (at least until .NET 4) unless you need more control. However, since it's not invoked very often, it probably doesn't matter...
Mark Seemann
A: 

You could also make the operation OneWay, so the client doesn't wait for the result of the operation. This would be the right choice, in my opinion, as you basically don't care about the result of the operation (mail failures, etc...). If you want to ensure delivery, you'll have to configure reliability for you service.

Philippe
There is a response that needs to be computed and send back to the caller so OneWay is not a good idea in this case.
GUZ