2

I am working on a larger website, and i would like to make "long running" parts of the program run on separated thread. But I am kind of torn on how to make this happen, and though I would ask if anyone have solved a similar issue. The reason I would like to this is because among other things I send emails to users and there a quite a few database lookups before the email is send, it would not be necessary to lock the user while all this happens. There are also other cases where I would like to wait some time to send the email, in case more emails are to be sending, and then combine them.

I have thought of 2 ways to do this:

  1. Have a thread running that is started in application state, that then will run the backend processing. This will enable me to send objects directly to the thread.
  2. Have a program running on the side, and send data to it via a table in my database.
Cœur
  • 37,241
  • 25
  • 195
  • 267
Androme
  • 2,399
  • 4
  • 43
  • 82

2 Answers2

3

Use a background process to do any heavy work that needs doing. Do not do it during your action method and do not spawn a thread to do the work from your action method: you risk spawning many threads if you get much activity at the same time.

I recommend using a Windows service for your background tasks if you can. This way, it could run on another computer than your web application if the need arises.

Use a database to store information about the background work to be done, but do not use a database table as "the queue of work". Use a proper queue for that:

  • Amazon SQS
  • Azure Message Bus
  • RabbitMQ

So, your action method would put the data needed for the background task in your database, then would push a message on your queue saying to do the work. Your background task would pop the message off the queue and access the database to get the work's data.

See:

Matt Houser
  • 33,983
  • 6
  • 70
  • 88
1

I recommend saving the 'work' to a db, and then having a service or job running that picks up on the work and does it. It is better from a security standpoint and you don't run into problems with trying to do long running tasks in the IIS worker threads.

What are some best practices for managing background threads in IIS?

Community
  • 1
  • 1
Lance Hudson
  • 151
  • 7