Using Thread.Sleep() in a Windows Service

后端 未结 5 1004
萌比男神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 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.

提交回复
热议问题