Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. To use or not to use worker thread in Windows Service?

To use or not to use worker thread in Windows Service?

Scheduled Pinned Locked Moved C#
csharpc++comquestion
14 Posts 7 Posters 6 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J JoeSchmoe007

    I am a newbie to C# development (have been doing C++ for years) and Windows Service implementation. While reading on the subject I found that there are 2 different approaches 1) Use timer event without additional worker thread - illustrated here: http://blogs.msdn.com/b/bclteam/archive/2005/03/15/396428.aspx[^] 2) Use worker thread - illustrated here: http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase%28VS.80%29.aspx[^] I seem to find the first approach simpler and easier to use. Can anyone explain if there are any drawbacks for this approach? Is there any reason to prefer worker thread approach?

    P Offline
    P Offline
    PIEBALDconsult
    wrote on last edited by
    #5

    I generally use a System.Timers.Timer -- they work for me. An additional benefit (to me anyway) is that the handler method enters and exits on each cycle rather than running indefinitely. In my opinion, the method shouldn't need to know that it is implementing a periodic function. Using a Timer allows me to separate responsibilities. The downside is that if the code takes longer to execute than the timer's interval, you wind up with two executions running at the same time -- you would need to allow for that or prevent it.

    J 1 Reply Last reply
    0
    • P PIEBALDconsult

      I generally use a System.Timers.Timer -- they work for me. An additional benefit (to me anyway) is that the handler method enters and exits on each cycle rather than running indefinitely. In my opinion, the method shouldn't need to know that it is implementing a periodic function. Using a Timer allows me to separate responsibilities. The downside is that if the code takes longer to execute than the timer's interval, you wind up with two executions running at the same time -- you would need to allow for that or prevent it.

      J Offline
      J Offline
      JoeSchmoe007
      wrote on last edited by
      #6

      Would this be a correct approach to prevent more than one execution:

          protected override void OnStart(string\[\] args)
          {
              WriteEventEntry("TestService starting...", EventLogEntryType.Information, 100, 100);
              timer.Elapsed += new ElapsedEventHandler(timer\_Tick);
              timer.Interval = 5000;
              timer.Enabled = true;
          }
      
          private void timer\_Tick(object sender, EventArgs e)
          {
              timer.Enabled = false; // stop timer to prevent more than one execution
              WriteEventEntry(DateTime.Now.ToString() + " timer ticked...", EventLogEntryType.Information, 100, 100);
              // do something useful here
              timer.Enabled = true; // start timer again
      
          }
      

      ?

      P 1 Reply Last reply
      0
      • J JoeSchmoe007

        Would this be a correct approach to prevent more than one execution:

            protected override void OnStart(string\[\] args)
            {
                WriteEventEntry("TestService starting...", EventLogEntryType.Information, 100, 100);
                timer.Elapsed += new ElapsedEventHandler(timer\_Tick);
                timer.Interval = 5000;
                timer.Enabled = true;
            }
        
            private void timer\_Tick(object sender, EventArgs e)
            {
                timer.Enabled = false; // stop timer to prevent more than one execution
                WriteEventEntry(DateTime.Now.ToString() + " timer ticked...", EventLogEntryType.Information, 100, 100);
                // do something useful here
                timer.Enabled = true; // start timer again
        
            }
        

        ?

        P Offline
        P Offline
        PIEBALDconsult
        wrote on last edited by
        #7

        Yes, but I suggest you use a try/catch/finally with the timer.Enabled = true; in the finally. (Unless you want your Service to stop when it encounters an Exception.)

        1 Reply Last reply
        0
        • J JoeSchmoe007

          I am a newbie to C# development (have been doing C++ for years) and Windows Service implementation. While reading on the subject I found that there are 2 different approaches 1) Use timer event without additional worker thread - illustrated here: http://blogs.msdn.com/b/bclteam/archive/2005/03/15/396428.aspx[^] 2) Use worker thread - illustrated here: http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase%28VS.80%29.aspx[^] I seem to find the first approach simpler and easier to use. Can anyone explain if there are any drawbacks for this approach? Is there any reason to prefer worker thread approach?

          G Offline
          G Offline
          Gonzalo Cao
          wrote on last edited by
          #8

          I mostly use threads, and if you want to keep the periodicity logic apart from the rest of the logic you can use something similar to this: while(true) { DoStuff(); sleep(1000); } The good thing about this, is that you running this code through a separate thread; thus it does not interfere with the UI thread. On large processes this will save you a lot of problems with the application not responding or working slower than expected. Anyway as someone else told you both solutions could work, I'd use timer for trivial tasks and the thread worker for more complex stuff, but that's just my choice.

          C 1 Reply Last reply
          0
          • J JoeSchmoe007

            I am a newbie to C# development (have been doing C++ for years) and Windows Service implementation. While reading on the subject I found that there are 2 different approaches 1) Use timer event without additional worker thread - illustrated here: http://blogs.msdn.com/b/bclteam/archive/2005/03/15/396428.aspx[^] 2) Use worker thread - illustrated here: http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase%28VS.80%29.aspx[^] I seem to find the first approach simpler and easier to use. Can anyone explain if there are any drawbacks for this approach? Is there any reason to prefer worker thread approach?

            R Offline
            R Offline
            RugbyLeague
            wrote on last edited by
            #9

            I use a timer, it just seems neater.

            1 Reply Last reply
            0
            • J JoeSchmoe007

              I am a newbie to C# development (have been doing C++ for years) and Windows Service implementation. While reading on the subject I found that there are 2 different approaches 1) Use timer event without additional worker thread - illustrated here: http://blogs.msdn.com/b/bclteam/archive/2005/03/15/396428.aspx[^] 2) Use worker thread - illustrated here: http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase%28VS.80%29.aspx[^] I seem to find the first approach simpler and easier to use. Can anyone explain if there are any drawbacks for this approach? Is there any reason to prefer worker thread approach?

              N Offline
              N Offline
              N a v a n e e t h
              wrote on last edited by
              #10

              JoeSchmoe007 wrote:

              Is there any reason to prefer worker thread approach?

              It depends on what you are trying to do. Timer is used when you want to get the callback in periodic intervals. One thing to note is, timer will fire the callback even if the previous call is in progress. All it does is queuing the job to a thread pool thread. If you don't have something to execute periodically, spawn a thread or use one from thread pool. I have seen people simulating the timer's behavior by spawning worker threads and sleeping on it, which is of course a bad design. There is no difference internally because both are using separate thread to do the job. :)

              Best wishes, Navaneeth

              J 1 Reply Last reply
              0
              • N N a v a n e e t h

                JoeSchmoe007 wrote:

                Is there any reason to prefer worker thread approach?

                It depends on what you are trying to do. Timer is used when you want to get the callback in periodic intervals. One thing to note is, timer will fire the callback even if the previous call is in progress. All it does is queuing the job to a thread pool thread. If you don't have something to execute periodically, spawn a thread or use one from thread pool. I have seen people simulating the timer's behavior by spawning worker threads and sleeping on it, which is of course a bad design. There is no difference internally because both are using separate thread to do the job. :)

                Best wishes, Navaneeth

                J Offline
                J Offline
                JoeSchmoe007
                wrote on last edited by
                #11

                Can you elaborate why sleeping on the worker thread is bad design? I see this approach used often. What design would you recommend instead when worker thread is used?

                N 1 Reply Last reply
                0
                • J JoeSchmoe007

                  Can you elaborate why sleeping on the worker thread is bad design? I see this approach used often. What design would you recommend instead when worker thread is used?

                  N Offline
                  N Offline
                  N a v a n e e t h
                  wrote on last edited by
                  #12

                  JoeSchmoe007 wrote:

                  Can you elaborate why sleeping on the worker thread is bad design?

                  Because Thread.Sleep may or may not sleep for more time than you specified. Take a look at this[^] article. IMO, the decision to use sleep is also subjective. If you need accuracy on the intervals, you should not use Thread.Sleep. If you are waitting for some condition to happen, say wait for an external device to be up, you should use WaitHandle instead of Thread.Sleep. Consider the following example: A windows service which is expected to do some job at every 10 minutes accurately (Eg: downloading a webpage and indexing the contents). You start the service and 12.00 and it should run at 12.10, 12.20 and so on. Unfortunatly the work took 15 minutes to complete. Now the program won't run at 12.20 instead it will run at 12.35. You loose the accuracy! This is where timers are useful.

                  JoeSchmoe007 wrote:

                  What design would you recommend instead

                  A windows service is something which is active all the time. If your application is doing the work only at specific intervals then it is not a good candidate for a service. It'd be better to create it as a normal console application and schedule it using the operating system's scheduler. :)

                  Best wishes, Navaneeth

                  1 Reply Last reply
                  0
                  • G Gonzalo Cao

                    I mostly use threads, and if you want to keep the periodicity logic apart from the rest of the logic you can use something similar to this: while(true) { DoStuff(); sleep(1000); } The good thing about this, is that you running this code through a separate thread; thus it does not interfere with the UI thread. On large processes this will save you a lot of problems with the application not responding or working slower than expected. Anyway as someone else told you both solutions could work, I'd use timer for trivial tasks and the thread worker for more complex stuff, but that's just my choice.

                    C Offline
                    C Offline
                    Chris Trelawny Ross
                    wrote on last edited by
                    #13

                    Hmm ... windows services don't have a UI thread :-O

                    G 1 Reply Last reply
                    0
                    • C Chris Trelawny Ross

                      Hmm ... windows services don't have a UI thread :-O

                      G Offline
                      G Offline
                      Gonzalo Cao
                      wrote on last edited by
                      #14

                      Touche!! And that's why my mamma told me I need to read the question before giving an answer :$

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups