This is my first attempt at creating a Windows service that calls multiple threads. What i did was create a console app, then added a windows service and installer to it. My code is below.
partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
System.Timers.Timer timer1 = new System.Timers.Timer();
timer1.Interval = 10000;
timer1.Start();
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
}
public static void timer1_Elapsed(object sender, EventArgs e)
{
Program.ThreadController();
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
class Program
{
static void Main(string[] args)
{
ThreadController();
}
public static void ThreadController()
{
for (int i = 0; i < 3; i++)
{
new Thread(() => { processEventLogTesting(); });
}
}
public static void processEventLogTesting()
{
EventLog.WriteEntry("ProcessThread1", "Process1 Works");
}
}
I’m not sure why i’m getting this error, any hints would be awesome.
Thanks.
First I’d add in some capability to do debugging. It’s actually easy (when you know how!!!).
Add this to your class:
Then add this to your main function (and you CAN do this too when running as a service if you enable the service to access the user interface by the way).
This gives you a console window and you can use Console.WriteLine to send output to it now. Yummy.
Now what you want to achieve, is for the service control manager to call your OnStart method, and then that method must RETURN the OK signal to let the SCM know that your app started up ok. Otherwise, SCM thinks something is wrong and kills your app. So OnStart is supposed to start your threads. So, make a Run() method that gets run by your thread (and by Main), and make OnStart return as fast as you can.
I notice I don’t see any of this in your code example:
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinService1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
I suspect that your app isn’t reporting to the SCM that it has successfully launched the “service” that is inside your executable.
You want your app to fire up, hand off the “service” to the SCM and let it know you are ok, and then return, while your service is now running with its own thread.
See this article for a great walk through:
http://msdn.microsoft.com/en-us/library/aa984464(v=vs.71).aspx