本文介绍了替代Thread.sleep代码()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每N分钟,我们想通过任务列表运行。因此,我们已经创建了一个任务执行与

  {做的DoWork(); }而(!STO prequested)

现在我们希望有工作周期之间的停顿。每个人似乎都认为Thread.sleep()方法是魔鬼。我已经看到了使用Monitor /事件东西提及,但我们没有别人告诉我们做的工作。我们只是希望做的东西像钟表每N分钟。

那么,有没有一种替代或有我发现了一个有效的利用了Thread.Sleep的?

有人在提到WaitHandle.WaitOne()作为替代另一篇文章,但你不能调用从非静态方法显然是?或者至少,我不能,因为我得到一个编译时错误。

解决方案

You have to call WaitOne on a WaitHandle, 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 use Monitor.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 (either System.Threading.Timer or System.Timers.Timer) or possibly even Quartz.NET.

这篇关于替代Thread.sleep代码()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:35
查看更多