C # code that works constantly - a service or a separate thread?

I have a .NET 4 web application that has three separate projects - DAL, BAL, and UI. I am using Entity Framework to interact with the database.

I have code that cycles through a collection of database data, calls methods depending on what it finds, and then updates the database. I want this code to work all the time. At the same time, I want users to be able to register and run reports, etc., while the code is constantly running in the background.

What is a good approach to this? Create a service for constantly running code, a separate thread, a completely separate project for code that works constantly, or another approach.?

Also, depending on the answers, how would I start to run code that works all the time? those. only through the form upload method or is there a better approach? I am currently running the code by clicking the "Start" button; This is great for testing, but is not going to work during the production process.

+4
source share
4 answers

It is best to use Windows Services for ongoing tasks .

Running code in a separate thread in IIS is not a reliable mechanism, since IIS can interrupt threads as it sees fit to conserve server resources.

+5
source

Given your question and clarifications on other answers that:

  • Your solution works in an environment where you cannot install the service;
  • Calling from a third server (such as Azure or such) is not an option for you;

You might be better off starting a thread in your Application_Start application to manage the database. You will probably want to make sure that this thread has had some periodic downtime so as not to overload too much hosted environment and ensure that it terminates when your application terminates or restarts.

The service will indeed be optimal, but if you are in a hosted environment and cannot / will not use another server, then this is not possible.

+2
source

Use the Windows service. You should also explore the use of stored procedures for the database interactions you mentioned. In terms of disabling the Windows service, you can configure it to automatically start (when the OS starts), which will mean that it will work until completion.

0
source

I would only recommend the Windows service if it works literally. However, β€œalways” usually means every x seconds / minutes / hours / days.

If x is more than a few minutes, I would make it a console application and run it through the Windows Task Scheduler. Thus, you do not need to worry about memory leaks and many other problems.

However, if it only works with a database, I would recommend a stored procedure and Sql Job.

0
source

All Articles