views:

225

answers:

2

Hi guys,

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 =)

+3  A: 

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

mfeingold
I do! If not, I can't see it in the process explorer and attach it!
Kovu
+6  A: 

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.

adrianbanks
That deserv to be flag as the answer since it is.
David Brunelle
Keep in mind that System.Threading.Timer and System.Timers.Timer run on separate threads and are not thread safe.
Aaron Fischer
I will test it that night and mark as a answer if it is - Aaron can you please add more infos about it?
Kovu
System.Windows.Forms.Timer runs on a single thread and fires its tick event on the UI thread. System.Threading.Timer and System.Timers.Timer fire their tick events on a ThreadPool thread.
adrianbanks