472,805 Members | 1,307 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,805 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 4366
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
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
How does React native implement an English player?
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.