This is my first window service that I am writing, I need some help in writing it, I am trying to use single thread so that one thread can start the service
and the other thread can take care of calling the functions that does the database work. I am also using a timer so that this service only runs once a day below is my code
The reason i am posting this question is whenever I tried to install this service, it is throwing an error saying “fatal error occure”, it doen’t give me any details.
public partial class Service1 : ServiceBase
{
private DateTime _lastRun = DateTime.Now;
Thread workerThread;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
ThreadStart st = new ThreadStart(WorkerFunction);
workerThread = new Thread(st);
serviceStarted = true;
workerThread.Start();
}
protected override void OnStop()
{
// flag to tell the worker process to stop
serviceStarted = false;
// give it a little time to finish any pending work
workerThread.Join(new TimeSpan(0, 2, 0));
timer1.Enabled = false;
}
private void WorkerFunction()
{
while (serviceStarted)
{
EventLog.WriteEntry("Service working",
System.Diagnostics.EventLogEntryType.Information);
// yield
if (serviceStarted)
{
Thread.Sleep(new TimeSpan(0, 20000, 0));
}
timer1.Enabled = true;
timer1.Start();
}
// time to end the thread
Thread.CurrentThread.Abort();
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_lastRun.Date < DateTime.Now.Date)
{
timer1.Stop();
// does the actual work that deals with the database
}
timer1.Start();
}
There’s a few things to check:
EventLogsource correctly (MSDN). My answer to Windows service Started and stopped automatically, exception handling issue could be useful here also.System.Threadingnamespace (MSDN).In particular, you may find the using a
System.Threading.Timerwill simplify your code a great deal as this object will manage a bit more of the plumbing for you.I would also advise against calling
Thread.Abort(): it can be harmful and unpredictable, and in your case it doesn’t appear that you need to use it at all. See To CurrentThread.Abort or not to CurrentThread.Abort andhttp://msdn.microsoft.com/en-us/library/5b50fdsz.aspx.