我正在製作我自己的調度程序,它將用於我的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