我正在制作我自己的调度程序,它将用于我的WPF应用程序之一。为调度程序选择正确的计时器
这是代码。
// Interface for a scheduled task.
public interface IScheduledTask
{
// Name of a task.
string Name { get; }
// Indicates whether should be task executed or not.
bool ShouldBeExecuted { get; }
// Executes task.
void Execute();
}
// Template for a scheduled task.
public abstract class PeriodicScheduledTask : IScheduledTask
{
// Name of a task.
public string Name { get; private set; }
// Next task's execute-time.
private DateTime NextRunDate { get; set; }
// How often execute?
private TimeSpan Interval { get; set; }
// Indicates whether task should be executed or not. Read-only property.
public bool ShouldBeExecuted
{
get
{
return NextRunDate < DateTime.Now;
}
}
public PeriodicScheduledTask(int periodInterval, string name)
{
Interval = TimeSpan.FromSeconds(periodInterval);
NextRunDate = DateTime.Now + Interval;
Name = name;
}
// Executes task.
public void Execute()
{
NextRunDate = NextRunDate.AddMilliseconds(Interval.TotalMilliseconds);
Task.Factory.StartNew(new Action(() => ExecuteInternal()));
}
// What should task do?
protected abstract void ExecuteInternal();
}
// Schedules and executes tasks.
public class Scheduler
{
// List of all scheduled tasks.
private List<IScheduledTask> Tasks { get; set; }
... some Scheduler logic ...
}
现在,我需要为调度程序选择正确的.net计时器。应该有订阅的事件滴答/经过内部,它通过任务列表并检查是否应该执行某个任务,然后通过调用task.Execute()
执行它。
一些更多的信息。我需要1秒的时间间隔设置,因为我创建的一些任务需要每秒钟,两次或更多时间执行。
我是否需要在新线程上运行计时器以启用用户在窗体上的操作?哪个计时器最适合此计划程序?
坦率地说,我首先想到的是DispatcherTimer,因为我的应用程序是基于WPF的。如果它不是必需的运行计时器在不同的线程中,System.Times.Timer和DispatcherTimer在新线程中执行taks有什么区别? – 2012-03-23 14:16:28
@安德鲁,我可能误解了你的问题。这听起来像你担心这个定时器运行时UI的响应性。 System.Timers.Timer在这方面的好处是它专为在多线程环境中使用而设计。如果您确实在单独的线程上运行它,则无论UI中发生了什么,它都应该能够及时触发。我没有使用过DispatchTimer,所以我真的不能谈论它。它可能会更好,你可能需要进一步研究。 – 2012-03-23 14:54:47