4

Hi I am new to windows service I have developed one windows service using the threading that creating new thread in OnStart() and running methods using that thread and using sleep thread to next run time but one of my friend said it is better to use timer than thread so I was wondering which is best way to do the program ? Thanks for the help

Ehsan88
  • 3,569
  • 5
  • 29
  • 52
  • 1
    threads and timers are *completely* different, `Thread.Sleep` is an awful method though if that is your question – Sayse Aug 02 '13 at 11:06
  • @Sayse Yes but what is better way to go for developing windows service –  Aug 02 '13 at 11:08
  • I have no idea what your windows service is, noone here will be able to answer that – Sayse Aug 02 '13 at 11:08
  • @user2553512 Is your goal to run some code at specific intervals (like each hour), and do nothing in between? – lightbricko Aug 02 '13 at 11:08
  • @lightbricko Yes i want to call one specific method from the web service in time interval so i was doing with the help of thread in windows service and sleeping the thread till next run –  Aug 02 '13 at 11:10

2 Answers2

3

Based on your comment that your goal is to run some code at specific intervals:

Conceptually it is better to use a timer than to make your thread sleep. This is what timers are made for. If you choose the thread sleep approach instead I think that in practice it will work fine anyways, although the better practice is to use timers.

There is a third approach - using a job scheduler. You can use windows task scheduler or the more powerful quartz.net (nuget package here).


This is really a question about how you value semantic correctness to pragmatism.

  • From a semantic correctness perspective the best approach is to use a job scheduler since you actually want to schedule a job.
  • From a pragmatic perspective the best approach is probably to just continue using the service you already developed even though it makes the thread sleep, and spend your time on something else than modifying your fully working code.

More opinions about timer vs. job scheduler: Best Timer for using in a Windows service

Community
  • 1
  • 1
lightbricko
  • 2,649
  • 15
  • 21
0

It depends on what you are doing i suppose. The difference betweeen Timer and Thread is that Timer uses a thread from the thread pool, whereas Thread dedicates a new one for the task.

You can read more here: http://social.msdn.microsoft.com/Forums/vstudio/en-US/c5b0e037-ccb5-42c0-bb0a-304572c8c8d2/timer-vs-thread-performance

Jocke
  • 673
  • 3
  • 8