Windows Service 需要等待,Thread.Sleep?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2588030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:13:50  来源:igfitidea点击:

Windows Service needs to wait, Thread.Sleep?

c#.netwindowsservice

提问by Dan H

I have a c# windows service that needs to execute a database query every 60 seconds (or whatever interval is set in the config file). I'm using Thread.sleep(60) in a while loop to accomplish this. Is there a better way to do this?

我有需要每 60 秒(或配置文件中设置的任何间隔)执行一次数据库查询的 ac# windows 服务。我在 while 循环中使用 Thread.sleep(60) 来完成此操作。有一个更好的方法吗?

Thanks

谢谢

回答by Reed Copsey

You can use a System.Threading.Timerto run your code every 60 seconds instead of doing it in a sleeping thread.

您可以使用System.Threading.Timer每 60 秒运行一次代码,而不是在休眠线程中运行。

回答by Russell Steen

It depends on what you want to do. If you want a (more) exact method you may want to use System.Threading.Timer. One thing about thread.sleep is that it really is "sleepatleastuntil...". The processor will ignore your thread until the sleep time is past. The next time it would give your thread priority, after the sleep time is past, it will.

这取决于你想做什么。如果你想要一个(更)精确的方法,你可能想要使用System.Threading.Timer。关于 thread.sleep 的一件事是它确实是“sleepatleastuntil...”。处理器将忽略您的线程,直到睡眠时间过去。下一次它会给你的线程优先级,在睡眠时间过去后,它会。

This will normally be very close to the desired interval, but could be longer. Don't yield unless you really intend to yield.

这通常非常接近所需的时间间隔,但可能会更长。除非你真的打算让步,否则不要让步。

回答by Justin Niessner

Use a Timerto fire the process every 60 seconds rather than force the process to sleep.

使用计时器每 60 秒触发一次进程,而不是强制进程休眠。