Question Where to put my code in a Windows Service skeleton

bradwoody

New member
Joined
Sep 21, 2011
Messages
2
Programming Experience
10+
I'm an ASP.Net sorta guy, but had to write a Windows app a while back. Now they want it to run as a service. I'm clueless.

I found a couple dozen examples of service skeletons, and I think they all originated with a MS post and everyone just copied that original one.

My skeleton runs fine and responds to Start and Stop in the Services Console. But when I put a call in to one of my classes, I'm just guessing where it should go.

I put the call to my stuff in OnStart, but my service never starts completely. I get:

ServiceError1.jpg

I saw an MS note that said:

ServiceError2.jpg


So knowing that I cannot have long-running code in OnStart, where (and how) do I call my stuff?

I apologize for the probably-obvious question, but I've got WAY too many hours in this and I've got to move on.

Thanks in advance,
Brad

Here's what I've got...:


namespace TeknoMLA
{
classProgram : ServiceBase
{

staticvoid Main(string[] args)
{
ServiceBase.Run(newProgram());
}


public Program()
{
this.ServiceName = "TeknoMLA";
}


protectedoverridevoid OnStart(string[] args)
{
base.OnStart(args);
TeknoMain.TeknoMLA_Main(); //this is the call to my class
}


protectedoverridevoid OnStop()
{
base.OnStop();
}

}//class
}//namespace
 
OnStart must return pretty much right away, so you can't make calls here that take, or could take, any significant time to complete. If you are starting some action that takes time you must do that in a secondary thread.
 
Hi John,

Thank you for the response. I really appreciate it.

I finally figured out that I needed to spawn a thread from OnStart. I really wish just one of the examples I found would have stated that. But instead of spawning an explicit thread, I allowed the timer to do it for me implicitely.

For anyone reading this in the future, here's what I did:

protectedoverridevoid OnStart(string[] args)
{
base.OnStart(args);

Timer DumbAssTimer = newTimer(RunMyStuff, null, 0, Timeout.Infinite);
Thread.Sleep(1000);
DumbAssTimer.Dispose();

}


privatestaticvoid RunMyStuff(Object state)
{
TeknoMain.TeknoMLA_Main();
}


I like to editorialize in my code with object names that reflect my frustration and/or opinion at the time.

Brad
 
Back
Top Bottom