473,545 Members | 529 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(stoppin g), 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.Con nect())
{
this.RaiseMessa ge("Found " + inbox.NumberOfM essages.ToStrin g() + "
messages for " + this.username);
foreach (MailMessage email in inbox)
{
if (!this.abort)
{
email.DownloadM essage();
email.Delete(fa lse);
}
}
}
this.inbox.Disc onnect();
}
}
public class MessageEventArg s : EventArgs
{
private readonly string msg;
public MessageEventArg s(string _msg)
{
this.msg = _msg;
}
public string Msg
{
get{return msg;}
}
}
Windows Service
=============== =============== =============== ======
using System;
using System.Diagnost ics;

public class Service1 : System.ServiceP rocess.ServiceB ase
{

private System.Diagnost ics.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 = "EmailScann er";
thread.IsBackgr ound = 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("E mail Processor Thread - Starting - Thread Culture: "
+ Thread.CurrentT hread.CurrentCu lture);

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

// Sink Message Event listener
processor.OnMes sage += new MessageEventHan dler(MessageAnn ouncer);

// Set POP3 settings
// cut for demo

// Process messages
processor.Proce ss();

// Release early
processor.Dispo se();

WriteMessage("E mail Processor Thread - Complete");

// yield
if (started)
{
Thread.Sleep(ne w TimeSpan(0, interval, 0));
}
}
catch(Exception ex)
{
ExHelper.Handle Exception(ex);
DoStop();
}
}
Thread.CurrentT hread.Abort();
}

void WriteMessage(st ring msg)
{
eventLog1.Write Entry(msg);
}

private void MessageAnnounce r(object sender, MessageEventArg s 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 4458
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(n ew 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.WriteMessa ge("Service is stopping");
this.started = false;
this.processor. Abort();

if (this.thread.Th readState != ThreadState.Uns tarted)
{
if (this.thread.Th readState == ThreadState.Wai tSleepJoin)
{
this.thread.Abo rt();
}
else
{
this.thread.Joi n(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
14109
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 the service, i get the following error Error 1053: The service did not respond to the start or control request in a timely fashion 1. Is there...
9
7239
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 stopping. Please advise how to stop the service. Thanks, SP
0
3604
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 are very high-performing on their own, make inexpensive database calls and use good caching to avoid excess database hits. However, when service 1...
1
2800
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
6880
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 (which is the UI used to adjust the actions taken by, and the schedule of the service), then a privileged user thread should be used in the UI - no...
10
1928
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 the service stops? Being new at this service stuff, I don't know if it holds state or memory and I need to stop all active timers or if the magical...
5
2733
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 access layer. The services layer contains WCF services, which use the business layer, which uses the resource access layer. I'm using data contracts...
9
2168
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 takes a long time to do this. In the meantime, the Timer1_Elapsed event fires again and a new thread seems to try and also tries to execute...
5
9133
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
7656
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7805
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7416
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7752
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5969
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5325
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4944
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1878
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.