2012-03-23 47 views
0

我正在制作我自己的调度程序,它将用于我的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秒的时间间隔设置,因为我创建的一些任务需要每秒钟,两次或更多时间执行。

我是否需要在新线程上运行计时器以启用用户在窗体上的操作?哪个计时器最适合此计划程序?

回答

1

我会使用System.Timers.Timer。从MSDN documentation

基于服务器的定时器是专为在 多线程环境中工作线程使用。服务器定时器可以在线程之间移动,以处理提升的Elapsed事件,从而导致比定时提升事件的Windows定时器更高的准确性。

我不认为你应该手动启动它在一个单独的线程。我从来没有从UI中盗取CPU时间,尽管我的开发主要是在Winforms中,而不是WPF。

+0

坦率地说,我首先想到的是DispatcherTimer,因为我的应用程序是基于WPF的。如果它不是必需的运行计时器在不同的线程中,System.Times.Timer和DispatcherTimer在新线程中执行taks有什么区别? – 2012-03-23 14:16:28

+0

@安德鲁,我可能误解了你的问题。这听起来像你担心这个定时器运行时UI的响应性。 System.Timers.Timer在这方面的好处是它专为在多线程环境中使用而设计。如果您确实在单独的线程上运行它,则无论UI中发生了什么,它都应该能够及时触发。我没有使用过DispatchTimer,所以我真的不能谈论它。它可能会更好,你可能需要进一步研究。 – 2012-03-23 14:54:47

0

您应该使用DispatcherTimer,因为它集成到调度队列中的同一个线程,它是创建(在你的情况下,UI线程)上:

DispatcherTimer timer = new DispatcherTimer(); 
timer.Interval = TimeSpan.FromSeconds(1); 
timer.Tick += new EventHandler(timer_Tick); 
timer.Start(); 
+0

好吧,我尝试过,但由于某种原因,它不起作用。所以我只改变了Timers.Timer的DispatcherTimer,并没有正常工作。这是一个谜。 – 2012-03-25 16:31:51

+0

@安德鲁什么不工作?你遇到了什么错误? – Slugart 2012-03-25 16:48:36

+0

就是这样。没有错误或例外。虽然定时器根据IsEnabled属性运行,但定时器根本不打勾。我不明白为什么它不起作用。 – 2012-03-26 11:43:48