[英]Choosing right timer for scheduler
我正在制作自己的調度程序,該調度程序將在我的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秒,因為我正在創建的某些任務需要每秒,兩次或更多次執行。
我是否需要在新線程上運行計時器以啟用用戶對表單的操作? 哪個計時器最適合此Scheduler?
我將使用System.Timers.Timer。 從MSDN文檔中 :
基於服務器的Timer設計用於多線程環境中的工作線程。 服務器計時器可以在線程之間移動以處理引發的Elapsed事件,與Windows計時器相比,按時引發事件的准確性更高。
我認為您不必在單獨的線程上手動啟動它。 盡管我的開發工作主要是Winforms,而不是WPF,但我從未從UI中竊取CPU時間。
您應該使用DispatcherTimer,因為它已與創建的同一線程(在您的情況下為UI線程)集成到調度程序隊列中:
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.