[英]Should I Thread.Sleep for a hours or there are more smarter way?
I have to update some data every 1 hour in a Thread. 我必须在线程中每1小时更新一些数据。 I put the Method-checker into a new Thread
我将方法检查器放入新的线程中
if ((time_now - last_update) < 3600)
Thread.Sleep(3600 * 1000);
But I feel like this isn't correct. 但是我觉得这是不正确的。 Maybe there is an elegant and inexpensive way to check for updates every hour without
Thread.Sleep
in C#? 如果没有C#中的
Thread.Sleep
,也许每小时都有一种优雅且便宜的方法来检查更新?
How about running your pulling method every fixed time: 如何每隔固定的时间运行一次拉动方法:
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromHours(1);
var timer = new System.Threading.Timer((e) =>
{
YourPullingMethod();
}, null, startTimeSpan, periodTimeSpan);
sleep should not be use. 睡眠不宜使用。 It is unreliable and can not be canceled;
它不可靠,无法取消; it is also blocking
它也阻塞了
you can do something like the following. 您可以执行以下操作。
object waitTimeOut = new object();
lock (waitTimeOut)
{
Monitor.Wait(waitTimeOut, TimeSpan.FromMilliseconds(3600 * 1000));
}
or 要么
TimeSpan ts = TimeSpan.FromMilliseconds(3600 * 1000);
t.Wait(ts)
Or with the low frequence you the other comments are good about using a cron job; 或者,如果您的频率较低,则其他评论对使用cron作业很有帮助; and would be much more suitable to what you are doing
会更适合您的工作
查看System.Threading.Timer
类(或其他计时器,使用最适合您的计时器)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.