简体   繁体   English

Windows服务需要等待,Thread.Sleep?

[英]Windows Service needs to wait, Thread.Sleep?

I have ac# windows service that needs to execute a database query every 60 seconds (or whatever interval is set in the config file). 我有一个ac #windows服务,需要每60秒执行一次数据库查询(或者在配置文件中设置任何间隔)。 I'm using Thread.sleep(60) in a while loop to accomplish this. 我在while循环中使用Thread.sleep(60)来完成此任务。 Is there a better way to do this? 有一个更好的方法吗?

Thanks 谢谢

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

It depends on what you want to do. 这取决于你想做什么。 If you want a (more) exact method you may want to use System.Threading.Timer . 如果你想要一个(更多)精确的方法,你可能想要使用System.Threading.Timer One thing about thread.sleep is that it really is "sleepatleastuntil...". 关于thread.sleep的一件事是它真的是“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. 下次它会给你的线程优先级,在睡眠时间过去之后,它会。

This will normally be very close to the desired interval, but could be longer. 这通常非常接近所需的间隔,但可能更长。 Don't yield unless you really intend to yield. 除非你真的打算屈服,否则不要屈服。

使用Timer每60秒触发一次进程,而不是强制进程进入休眠状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM