Skip to content Skip to sidebar Skip to footer

C# Code That Run Constantly - Service Or Separate Thread?

I have a .NET 4 web application that has 3 separate projects associated – DAL, BAL, and UI. I am using Entity Framework for database interaction. I have code that cycles through

Solution 1:

You would be best suited for using Windows Services for always-running tasks.

Running code on a separate thread under IIS is not a reliable mechanism since IIS can terminate threads at will to conserve server resources.


Solution 2:

Given your question and clarifications on other answers that:

  1. Your solution runs in a hosted environment where you cannot install a service;
  2. Calling it from a third server (i.e. Azure or such) is not an option for you;

You might be best off starting a thread in your Application_Start event to manage the database work. You'd probably want to ensure that this thread had some periodic idle time, so as not to take up too much of the hosted environment and ensure it's shutdown when your application ends or is restarted.

A service would really be optimal, but if you're in a hosted environment and can't/won't use another server, then that's not possible.


Solution 3:

Use a Windows Service. Should also look into using Stored Procs for the database interactions you mentioned. In terms of kicking the Windows Service off, you can set it to automatic startup (when the OS starts) which will mean it will run until terminated.


Solution 4:

I would only recommend a Windows Service if it will literally always be running. However, "always" usually means every x seconds / minutes / hours /days.

If x is greater than a few minutes, I would make it a Console Application and run it through the Windows Task Scheduler. This way you don't have to worry about memory leaks and a slew of other issues.

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


Post a Comment for "C# Code That Run Constantly - Service Or Separate Thread?"