替代Thread.sleep代码() [英] Alternatives to Thread.Sleep()
问题描述
每N分钟,我们想通过任务列表运行。因此,我们已经创建了一个任务执行与
{做的DoWork(); }而(!STO prequested)
现在我们希望有工作周期之间的停顿。每个人似乎都认为Thread.sleep()方法是魔鬼。我已经看到了使用Monitor /事件东西提及,但我们没有别人告诉我们做的工作。我们只是希望做的东西像钟表每N分钟。
那么,有没有一种替代或有我发现了一个有效的利用了Thread.Sleep的?
有人在提到WaitHandle.WaitOne()作为替代另一篇文章,但你不能调用从非静态方法显然是?或者至少,我不能,因为我得到一个编译时错误。
需要一个对象引用
非静态字段,方法或
属性
System.Threading.WaitHandle.WaitOne(System.TimeSpan)
块引用>解决方案您必须调用
的WaitOne
的在的一个WaitHandle的
,肯定。这是一个实例方法。否则怎么会知道等待什么?这绝对是最好有的东西的可以应对,而不是睡眠,让你无需等待分钟无故取消通知。另一种替代
的WaitHandle
是使用Monitor.Wait
/脉冲
。不过,如果你使用.NET 4我想看看成什么任务并行库所提供的...这是比其他选项稍高,一般是一个深思熟虑的库。
有关日常工作任务,你可能想看看使用
定时
(或System.Threading.Timer
或System.Timers.Timer
),甚至可能是 Quartz.NET 。Every N minutes we want to run through a list of tasks. So we've created a task executor with a
do { DoWork(); }while(!stopRequested)
Now we want to have a pause between work cycles. Everyone seems to think Thread.Sleep() is the devil. I've seen mention of using Monitor/Event stuff but we don't have someone else telling us to do work. We just want to do stuff every N minutes like clockwork.
So is there an alternative or have I found a valid use of Thread.Sleep?
Someone in another post mentioned WaitHandle.WaitOne() as an alternative but you can't call that from a non-static method apparently? Or at least I can't because I get a compile time error of..
An object reference is required for the non-static field, method, or property 'System.Threading.WaitHandle.WaitOne(System.TimeSpan)'
解决方案You have to call
WaitOne
on aWaitHandle
, certainly. It's an instance method. Otherwise how would it know what to wait for?It's definitely better to have something you can react to instead of sleep, so that you can notice cancellation without waiting minutes for no reason. Another alternative to
WaitHandle
is to useMonitor.Wait
/Pulse
.However, if you're using .NET 4 I'd look into what the Task Parallel Library has to offer... it's at a slightly higher level than the other options, and is generally a well thought out library.
For regular work tasks you might want to look at using a
Timer
(eitherSystem.Threading.Timer
orSystem.Timers.Timer
) or possibly even Quartz.NET.这篇关于替代Thread.sleep代码()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!