C# – ASP.NET Threading: should I use the pool for DB and Emails actions

asp.netasynchronouscmultithreading

I’m looking for the best way of using threads considering scalability and performance.

In my site I have two scenarios that need threading:

  1. UI trigger: for example the user clicks a button, the server should read data from the DB and send some emails. Those actions take time and I don’t want the user request getting delayed. This scenario happens very frequently.

  2. Background service: when the app starts it trigger a thread that run every 10 min, read from the DB and send emails.

The solutions I found:

A. Use thread pool – BeginInvoke:
This is what I use today for both scenarios.
It works fine, but it uses the same threads that serve the pages, so I think I may run into scalability issues, can this become a problem?

B. No use of the pool – ThreadStart:
I know starting a new thread takes more resources then using a thread pool.
Can this approach work better for my scenarios?
What is the best way to reuse the opened threads?

C. Custom thread pool:
Because my scenarios occurs frequently maybe the best way is to start a new thread pool?

Thanks.

Best Answer

I would personally put this into a different service. Make your UI action write to the database, and have a separate service which either polls the database or reacts to a trigger, and sends the emails at that point.

By separating it into a different service, you don't need to worry about AppDomain recycling etc - and you can put it on an entire different server if and when you want to. I think it'll give you a more flexible solution.