A recommended Windows Service architecture with a single timed thread?

B

benmorganpowell

I have a small windows service which connects to a POP3 server at
defined intervals, scans the available messages, extracts the required
information and inserts the data into a SQL database. I am assuming
that this is not an uncommon piece of software.

I want to get an architecture that conforms as closely as possible with
the recommendations from Microsoft on developing Windows Services, but
to be honest I have found difficultly in finding good resources. I
hope someone can point me in the right direction. I currently have a
component that connects to the POP3 server and loops through each
message until finished. The component is called via a thread ina
windows service which after processing will sleeps for a defined
interval. Within the component I have created a public property so that
the component can know that the containing service is stopping and that
it should abort. Hence the loop can check whether it should abort
gracefully at each iteration of the loop (every email), but I cannot
establish how to set the property in the component.

The key requirements are as follows:

POP3:
---------------------------------------
Email should never be "lost". Therefore an email must have been
inserted into the database or forwarded to another email account as a
FormatException (non conformation to the required format in the email),
before it can be deleted.

Exceptions:
---------------------------------------
Exceptions are passed up the chain to the containing service code
Exceptions are logged in the event log
Exceptions regarding connectivity (database/pop3/SMTP) put the thread
to sleep rather than stop the service

Threading Architecture:
---------------------------------------
The service must run and exit gracefully. Hence when the service is
stopped(stopping), I would want it to wait until the current email has
been dealt with before aborting. The thread must sleep for a defined
interval before going through the same process again. Should I keep the
same single thread running over and over again, or create a new thread
on every cycle?

So, the basic architecture I have at present is this:

Processor Component:
===================================================
public class Processor
{
private bool abort;

public bool Abort
{
set{ abort = value; }
}

// other properties to set POP3 host/username/password etc
// removed

public void Processor()
{
// setup inbox
// cut for demonstration
}

public void Process()
{
if (this.inbox.Connect())
{
this.RaiseMessage("Found " + inbox.NumberOfMessages.ToString() + "
messages for " + this.username);
foreach (MailMessage email in inbox)
{
if (!this.abort)
{
email.DownloadMessage();
email.Delete(false);
}
}
}
this.inbox.Disconnect();
}
}
public class MessageEventArgs : EventArgs
{
private readonly string msg;
public MessageEventArgs(string _msg)
{
this.msg = _msg;
}
public string Msg
{
get{return msg;}
}
}


Windows Service
===================================================
using System;
using System.Diagnostics;

public class Service1 : System.ServiceProcess.ServiceBase
{

private System.Diagnostics.EventLog eventLog1;

private Thread thread;
private int interval;
private bool started;

protected override void OnStart(string[] args)
{
DoStart();
}

protected override void OnStop()
{
DoStop();
}

void DoStart()
{
thread = new Thread(new ThreadStart(Job));
thread.Name = "EmailScanner";
thread.IsBackground = false;

started = true;
interval = 20; //minutes

thread.Start();
}

void DoStop()
{
started = false;
thread.Join(new TimeSpan(0, 2, 0));
}

void Job()
{
while (started)
{
try
{
WriteMessage("Email Processor Thread - Starting - Thread Culture: "
+ Thread.CurrentThread.CurrentCulture);

// Create new Processor
Processor processor = new Processor();

// Sink Message Event listener
processor.OnMessage += new MessageEventHandler(MessageAnnouncer);

// Set POP3 settings
// cut for demo

// Process messages
processor.Process();

// Release early
processor.Dispose();

WriteMessage("Email Processor Thread - Complete");

// yield
if (started)
{
Thread.Sleep(new TimeSpan(0, interval, 0));
}
}
catch(Exception ex)
{
ExHelper.HandleException(ex);
DoStop();
}
}
Thread.CurrentThread.Abort();
}

void WriteMessage(string msg)
{
eventLog1.WriteEntry(msg);
}

private void MessageAnnouncer(object sender, MessageEventArgs e)
{
WriteMessage(e.Msg);
}
}

Question really is - how I message this.processor.Abort. I am guessing
that I define Processor as a global variable. In that way I can then
try and tie in the OnStop event of the Windows Service? Is this how it
should be done?

Do I have a good architecture for this? Am I approaching this in the
right way? Any kindly advice is welcomed.

Regards

Ben
 
B

benmorganpowell

I have in some ways managed to solve the problem of notifying my
threaded job that it should terminate gracefully. However, I have a
question regarding Thread.Sleep().

If the Windows Service is being stopped, the OnStop() Event is called,
which in turn with my code triggers a Thread.Join(). However, a thread
that is asleep (Thread.Sleep(new TimeSpan(0,2,0)), will have to wait
until it again resumes before it stops.

How can I kill a thread straight away, but ONLY when it is in a Sleep
state? I have this working using Thread.Abort(), but I'm not sure if it
is the proper way to do it:

void StopThread()
{
this.WriteMessage("Service is stopping");
this.started = false;
this.processor.Abort();

if (this.thread.ThreadState != ThreadState.Unstarted)
{
if (this.thread.ThreadState == ThreadState.WaitSleepJoin)
{
this.thread.Abort();
}
else
{
this.thread.Join(new TimeSpan(0, 2, 0));
}
}
}

I welcome your advice. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top