469,917 Members | 1,642 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,917 developers. It's quick & easy.

A recommended Windows Service architecture with a single timed thread?

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:

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 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)
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)

protected override void OnStop()

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

started = true;
interval = 20; //minutes


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

void Job()
while (started)
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

// Release early

WriteMessage("Email Processor Thread - Complete");

// yield
if (started)
Thread.Sleep(new TimeSpan(0, interval, 0));
catch(Exception ex)

void WriteMessage(string msg)

private void MessageAnnouncer(object sender, MessageEventArgs e)

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.



Nov 17 '05 #1
1 4040
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;

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

I welcome your advice. :-)

Nov 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Richard Steele | last post: by
9 posts views Thread by SP | last post: by
5 posts views Thread by ludwig_stuyck | last post: by
9 posts views Thread by brendan_gallagher_2001 | last post: by
reply views Thread by Salome Sato | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.