I wrote my first windows service.
- Create WS project
- Rename Service
- Drag a timer into the middle
- Enable it, tick to 1s
- Create a logfie in tick when not exists
- Install the service
- Run the Service
Nothing happens…
I try to attach to the service, it’s loaded correctly, but with a breakpoint in it, it never hits.
Any ideas?
Code Timer:
private void timMain_Tick(object sender, EventArgs e)
{
if (!File.Exists("C:/test.txt"))
File.Create("C:/test.txt");
}
Code initialize:
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.timMain = new System.Windows.Forms.Timer(this.components);
//
// timMain
//
this.timMain.Enabled = true;
this.timMain.Interval = 1000;
this.timMain.Tick += new System.EventHandler(this.timMain_Tick);
//
// AuctionService
//
this.CanShutdown = true;
this.ServiceName = "AuctionService";
}
One word: The File.Create is only to test if the timer tick. I was a little uncreatve because of that =)
Even though you are initialising the timer correctly, it is not doing anything because you are not using it in a UI. The MSDN docs state that it must be used with a UI message pump, which a service does not have.
I recommend you use a System.Threading.Timer instead as it does not require a UI and is more appropriate for use in a service:
Note that the tick event handler for this timer only takes an
objectas an argument.