您可以声明一个基Task
类或接口,无论您喜欢哪个实现bool
属性NeedsToRun
和方法Run()
。
然后,您可以为每个单独的任务(或使用委托函数、任务类型)继承 Task 类,并定义您需要的所有自定义要求,以检查该任务是否需要运行,如果需要,请调用该Run()
特定任务的方法。
将所有任务添加到 aList<Task>
并定期迭代它们以查看实际需要运行的任务,瞧;你有一个非常简单但有效的调度程序。
就个人而言,我追求的是基于优先级的调度程序,而不是你描述的事件驱动的调度程序,所以我实现了一个Func<bool>
来确定一个任务是否需要运行并Action
实际运行它。我的代码如下:
public class Task : IComparable<Task>
{
public Task(int priority, Action action, Func<bool> needsToRun, string name = "Basic Task")
{
Priority = priority;
Name = name;
Action = action;
_needsToRun = needsToRun;
}
public string Name { get; set; }
public int Priority { get; set; }
private readonly Func<bool> _needsToRun;
public bool NeedsToRun { get { return _needsToRun.Invoke(); } }
/// <summary>
/// Gets or sets the action this task performs.
/// </summary>
/// <value>
/// The action.
/// </value>
public Action Action { get; set; }
public void Run()
{
if (Action != null)
Action.Invoke();
}
#region Implementation of IComparable<in State>
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo(Task other)
{
return Priority == other.Priority && Name == other.Name ? 1 : 0;
}
#endregion
}
但我认为这可以适应订阅事件并设置一个标志,以确保NeedsToRun
在该事件被相当容易地触发时返回 true。