Using Thread.Sleep() in a Windows Service

后端 未结 5 1002
萌比男神i
萌比男神i 2021-02-04 07:46

I\'m writing a windows service that needs to sleep for long periods of time (15 hrs is the longest it will sleep, 30 mins is the shortest). I\'m currently using Thread.

相关标签:
5条回答
  • 2021-02-04 07:48

    I would use a timer, Thread.Sleep, could cause a blocking piece that could prevent the service from shutting down.

    If the interval is that wide spread, and regular, you might just schedule it as well. But if you are talking about long, non-consistent intervals, then yes a Timer would be better.

    0 讨论(0)
  • 2021-02-04 07:54

    It's generally regarded as bad practice to use Thread.Sleep() in a lot of cases.

    If you want the service to run in the background, you should use a timer.

    If the service only needs to be run at scheduled intervals, I'd recommend you look into using Windows task scheduler to allow Windows to run the application when you need it to.

    0 讨论(0)
  • 2021-02-04 07:55

    You should not pre-calculate such large amounts of time and sleep for hours. Sleep for a minute at best, then wake up and re-calculate the time, sleep again for no more that a minute. I assume the calculation is very cheap or it can be made very cheap with caching. The problem my advise is trying to mitigate is that computer clocks are surprisingly 'jumpy', mostly due to time drift corrected by network time service, also because of daylights savings and not least because user adjusting the clock. So is better to constantly recompute the time for such long intervals, even if it means waking up every minute or so. And don't be surprised (ie. don't assert) if you wake up in the 'past', clocks can adjust back in time.

    0 讨论(0)
  • 2021-02-04 08:07

    Since a service may be asked to stop at any time by the Service Control Manager, your thread should always be ready to respond to these requests, so you should not use Thread.Sleep(). Instead, create a manual-reset event in the main thread and use its WaitOne method with a timeout in your worker thread. WaitOne will return false when the time expires.

    When your service class's OnStop or OnShutdown methods are called, set the event and that will cause WaitOne to return true and you can then exit your worker thread.

    0 讨论(0)
  • 2021-02-04 08:10

    Another thing to consider is that threads are finite resources and each thread consumes a portion of memory (1MB?) for the its stack. They may also increase load for the scheduler.

    Now, if your service isn't doing much else the wasted space is trivial, but it is wise to be aware of this before you start allocating multiple threads. Using a ThreadPool and/or Timers is much more efficient.

    0 讨论(0)
提交回复
热议问题