简体   繁体   中英

First Windows Service - timer seems not to tick

I wrote my first windows service.

  1. Create WS project
  2. Rename Service
  3. Drag a timer into the middle
  4. Enable it, tick to 1s
  5. Create a logfie in tick when not exists
  6. Install the service
  7. 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:

Timer t = new Timer(t_Tick, null, 0, 1000);

Note that the tick event handler for this timer only takes an object as an argument.

How do you "Run the Service"? You have to start the service through the Service manager. Running it from the VS does not do it. If you want to debug it you still need to start it through the service manager and then attach the debugger when it is already running

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM