C# 计时器或 Thread.Sleep
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1091710/
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
C# Timer or Thread.Sleep
提问by Adonis L
I am running a windows service and using a loop and Thread.Sleep to repeat a task, would it be better to use a timer method?
我正在运行 Windows 服务并使用循环和 Thread.Sleep 来重复任务,使用计时器方法会更好吗?
If yes a code example would be great
如果是,代码示例会很棒
I am currently using this code to repeat
我目前正在使用此代码重复
int curMinute;
int lastMinute = DateTime.Now.AddMinutes(-1).Minute;
while (condition)
{
curMinute = DateTime.Now.Minute;
if (lastMinute < curMinute) {
// do your once-per-minute code here
lastMinute = curMinute;
}
Thread.Sleep(50000); // sleeps for 50 seconds
if (error condition that would break you out of this) {
break; // leaves looping structure
}
}
采纳答案by Prashanth
class Program
{
static void Main(string[] args)
{
Timer timer = new Timer(new TimerCallback(TimeCallBack),null,1000,50000);
Console.Read();
timer.Dispose();
}
public static void TimeCallBack(object o)
{
curMinute = DateTime.Now.Minute;
if (lastMinute < curMinute) {
// do your once-per-minute code here
lastMinute = curMinute;
}
}
The code could resemble something like the one above
代码可能类似于上面的代码
回答by Christopher Karper
It's important to understand that your code will sleep for 50 seconds between ending one loop, and starting the next...
重要的是要了解您的代码将在结束一个循环和开始下一个循环之间休眠 50 秒......
A timer will call your loop every 50 seconds, which isn't exactly the same.
计时器将每 50 秒调用一次您的循环,这并不完全相同。
They're both valid, but a timer is probably what you're looking for here.
它们都是有效的,但计时器可能是您在这里寻找的东西。
回答by Jon Norton
Yes, using a Timer will free up a Thread that is currently spending most of its time sleeping. A Timer will also more accurately fire every minute so you probably won't need to keep track of lastMinute
anymore.
是的,使用 Timer 将释放当前大部分时间都在休眠的线程。计时器也会更准确地每分钟触发一次,因此您可能不再需要跟踪lastMinute
。
回答by Jon Skeet
A timer is a better idea, IMO. That way, if your service is asked to stop, it can respond to that very quickly, and just not call the timer tick handler again... if you're sleeping, the service manager will either have to wait 50 seconds or kill your thread, neither of which is terribly nice.
计时器是一个更好的主意,IMO。这样,如果您的服务被要求停止,它可以非常快速地响应,并且不会再次调用计时器滴答处理程序......如果您正在睡觉,服务管理器将不得不等待 50 秒或杀死您的线程,这两个都不是非常好。
回答by cjk
Not quite answering the question, but rather than having
没有完全回答这个问题,而是没有
if (error condition that would break you out of this) {
break; // leaves looping structure
}
You should probably have
你应该有
while(condition && !error_condition)
Also, I'd go with a Timer
.
另外,我会选择一个Timer
.
回答by Umair Ahmed
You can use either one. But I think Sleep()
is easy, clear and shorter to implement.
您可以使用任何一种。但我认为实施起来Sleep()
很容易、清晰且更短。
回答by Philippe Leybaert
Beware that calling Sleep() will freeze the service, so if the service is requested to stop, it won't react for the duration of the Sleep() call.
请注意,调用 Sleep() 会冻结服务,因此如果服务被请求停止,则它不会在 Sleep() 调用期间做出反应。
回答by Simon Temlett
I required a thread to fire once every minute (see question here) and I've now used a DispatchTimer
based on the answers I received.
我需要一个线程每分钟触发一次(请参阅此处的问题),现在我DispatchTimer
根据收到的答案使用了一个。
The answers provide some references which you might find useful.
答案提供了一些您可能会觉得有用的参考资料。
回答by Nick DeMayo
I agree as well, using a timer is the best option. I have tried a solution similar to yours in the past and started having issues where the loop would misfire, and I would have to wait for another Thread.Sleep() before it would fire again. Also, it did cause all sorts of issues with stopping the service, I would get constant errors about how it wasn't responding and had to be closed.
我也同意,使用计时器是最好的选择。我过去曾尝试过与您类似的解决方案,并开始遇到循环不触发的问题,我必须等待另一个 Thread.Sleep() 才能再次触发。此外,它确实导致了停止服务的各种问题,我会不断收到关于它如何没有响应并且不得不关闭的错误。
@Prashanth's code should be exactly what you need.
@Prashanth 的代码应该正是您所需要的。
回答by jwhitley
I have used both timers and Thread.Sleep(x), or either, depending on the situation.
我已经使用了计时器和 Thread.Sleep(x),或者两者之一,这取决于具体情况。
If I have a short piece of code that needs to run repeadedly, I probably use a timer.
如果我有一小段代码需要重复运行,我可能会使用计时器。
If I have a piece of code that might take longer to run than the delay timer (such as retrieving files from a remote server via FTP, where I don't control or know the network delay or file sizes / count), I will wait for a fixed period of time between cycles.
如果我有一段代码的运行时间可能比延迟计时器要长(例如通过 FTP 从远程服务器检索文件,我无法控制或知道网络延迟或文件大小/计数),我会等待循环之间的固定时间段。
Both are valid, but as pointed out earlier they do different things. The timer runs your code every x milliseconds, even if the previous instance hasn't finished. The Thread.Sleep(x) waits for a period of time after completing each iteration, so the total delay per loop will always be longer (perhaps not by much) than the sleep period.
两者都是有效的,但正如前面指出的那样,它们做不同的事情。计时器每 x 毫秒运行一次您的代码,即使前一个实例尚未完成。Thread.Sleep(x) 在完成每次迭代后会等待一段时间,因此每个循环的总延迟将始终比睡眠时间长(可能不会太多)。