Reputation: 329
I have a windows service to do the background process. This windows service will interact to asp.net website. The functionality is as below.
In my website 3 actions are there. User can choose the task (suppose three buttons are there). Then it will call the windows service. The rest of the operation is performed by windows service. User can log out from the website, but it will run the service in background. Once it is finished it will make corresponding changes in database. I need to know whether I can apply any design pattern to the windows service (factory, abstract factory etc.). I have read about different design patterns, but I am really confused about how this applied to a project. Currently I am writing the entire code in ‘OnStart’ and ‘OnStop’ events of windows service. Please guide me.
Thanks.
Upvotes: 3
Views: 3054
Reputation: 6299
The only time I install multiple instances of services is for multiple environments, such as development, test, and production. Otherwise, it should be kept in the same service, assuming all of the code is logically relevant.
As for design pattern, I've been following a simple "pattern" for most services I create. I encourage answers as I myself don't know if this is a good pattern. It basically involves creating a master thread that is immediately started, and child threads based on what needs to be done. For your situation, the below could be a simple service layout for a user processor.
The Service class:
public partial class Service : ServiceBase
{
private Processor _processor;
public Service() { InitializeComponent(); }
protected override void OnStart(string[] args)
{
_processor = new Processor();
new System.Threading.Thread(_processor.Run).Start();
}
protected override void OnStop()
{
_processor.Stop();
}
}
Processor:
public class Processor
{
private bool _continue;
private List<UserProcessor> _userProcessors; // List of users being processed.
public void Run()
{
_continue = true;
while (_continue)
{
var users = getUsersToProcess();
foreach (User user in users)
{
if (_userProcessors.Any(u => u.UserId == user.UserId) == false)
{
// Start a new processor for the user since it wasn't found.
var processor = new UserProcessor(user);
new System.Threading.Thread(processor.Run).Start();
_userProcessors.Add(processor);
}
}
System.Threading.Thread.Sleep(1000);
}
}
public void Stop()
{
_continue = false;
foreach (var processer in _userProcessors)
processer.Stop();
}
private List<User> getUsersToProcess() { throw new NotImplementedException(); }
}
And of course, UserProcessor is nearly setup the same as Processor, but with different code inside of the while loop. This is where you would do your database interaction, but I'll let you figure this part out.
Upvotes: 6