For a project at work, I was tasked to create a WCF service that will receive email messages from client and queue them on a database, while at the same time the service will check the DB every 30 minutes or so to check if there are any new email messages queued, and send them automatically with the appropriate credentials.
To accomplish this, my boss told me to do it with threads: while the main thread is in charge of taking requests from clients, a background thread will be in charge of checking the DB for as long as the service is alive, and send the queued emails. After asking on StackOverflow, however, I was told that for this kind of scenario two services is a better option, a WCF service that takes requests and a different Windows Service that does the background work.
So my question is, what is the best option for implementing this kind of scenario? And is doing this with just threads possible, but ill-advised? I would like to hear more opinions before checking with my boss about the best way to accomplish this.
Best Answer
If you host your WCF service on IIS:
Running long tasks from a web application which uses IIS is a bad idea:
IIS recycles AppDomains at regular intervals; this may not be what you want if you're in the middle of a long task.
IIS recycles AppDomain when files such as web.config are updated.
It may negatively impact performance.
So yes, if you need a background task, use a Windows Service instead.
Sources:
ASP.NET long running task. Thread is being aborted exception
What causes an application pool in IIS to recycle?
Can I use threads to carry out long-running jobs on IIS?
How should I perform a long-running task in ASP.NET 4?
If you run your WCF service as a Windows Service:
Separating Windows Service hosting your WCF application from the Windows Service which does the background processing can have two benefits:
If one of the services crashes, the second one is not affected. This is a minor benefit, since if one of the services crashes, you may have more urgent concerns.
You may host each service on a dedicated server. This benefit is also probably minor, unless you're processing a lot of information.
As for using a single service and two threads, I don't see any blocking issue as when the service is hosted on IIS.