473,406 Members | 2,956 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

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:

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

Nov 17 '05 #1
1 4442
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. :-)

Nov 17 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Richard Steele | last post by:
I have created a WinForm application that needs to be run as a windows service (the PC is inaccesible by any user) i have successfully installed the application as a windows service. When i start...
9
by: SP | last post by:
Hi All, I wrote a windows service which is supposed to stop after specified amount of time. I am calling OnStop() after specified time. OnStop() methods executed but I dont see the service...
0
by: Barb | last post by:
Hello, I have a (C#) web service being consumed by a high volume "asp classic" site. It worked perfectly until I tried consuming a second web service from the first web service. Both services...
1
by: reaway | last post by:
When I call Web Service by mulithread just like the following: public class test { public void Execute() { while(....) { ThreadPool.QueueUserWorkItem(new WaitCallback(DoProcess),request); }
2
by: deko | last post by:
When to use a privileged user thread rather than a windows service? That's the question raised in a previous post . It was suggested that if the service needs to interact with a WinForms app...
10
by: Ryan | last post by:
Hello everyone, I have made a service that starts timers when it starts. I have another windows form application that stops and starts the service. Do I need to deal with any started timers when...
5
by: ludwig_stuyck | last post by:
I'm in the process of designing a Service Oriented Architecture. At the moment I based the design on the Web Service Software factory guidelines - so a services layer, business layer and resource...
9
by: brendan_gallagher_2001 | last post by:
Hi I am seeing some strange behaviour on a windows (vb.net 1.1) service. Basically, what I see happening is that when the Timer1_Elapsed event fires, it attempts to execute Timer1.Stop() but...
5
by: Max2006 | last post by:
Hi, I am trying to limit my wcf service endpoint to response to only given windows user or group. How can I do that? Is there any way to configure that in the .config file? Thank you, Max
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.