在 C# 中安排任务的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/752326/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:48:40  来源:igfitidea点击:

Best way to schedule tasks in C#

c#.net

提问by Whiteknight

I'm developing a C# program that needs to be able to schedule a variety of asynchronous tasks at different times. I need a solution that activates every second to check for tasks to execute, and eats up as few resources as possible. It also needs to scale well to a large number of tasks. Which of these is better to use, or is there any ?

我正在开发一个 C# 程序,它需要能够在不同时间安排各种异步任务。我需要一个解决方案,每秒激活一次以检查要执行的任务,并尽可能少地消耗资源。它还需要很好地扩展到大量任务。其中哪一个更好用,或者有没有?

1) Using a System.Timers.Timer object with a 1 second elapsed time to trigger an event that executes tasks, or

1) 使用具有 1 秒经过时间的 System.Timers.Timer 对象来触发执行任务的事件,或

2) Using a separate thread that sleeps for 1 second and then executes tasks when it wakes up, or

2) 使用一个单独的线程,它会休眠 1 秒,然后在它醒来时执行任务,或者

3) Something else entirely.

3)完全不同的东西。

采纳答案by Michael Haren

System.Threading.Timeris extremely lightweight. You could create a separate timer for each task so that the timer comes due when the task is supposed to execute.

System.Threading.Timer非常轻巧。您可以为每个任务创建一个单独的计时器,以便在任务应该执行时计时器到期。

Internally, I believe that the system will keep track of what timer is due next so it only has to monitor one timer at any given time (source/similar question).

在内部,我相信系统会跟踪下一个到期的计时器,因此它只需要在任何给定时间监视一个计时器(来源/类似问题)。

回答by ZombieSheep

Try looking at Quartz.Netfor your scheduling needs. I think it's pretty good.

尝试查看Quartz.Net以满足您的调度需求。我觉得还不错。