I am writing a task scheduler (that will one day grow up to be a windows service when I look into them) that should pretty much loop infinitely until I tell the program to stop. But having while(true)
seems incorrect. What is the correct way to implement the loop? Use a dummy boolean variable that the code doesn't actually set to false ever (or should it set to false in a catch
whose try
encompasses the whole inside of the loop?)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataPump
{
class TaskManager
{
// Tasks added externally on an instance of TaskManager
public Dictionary<DatapumpTask, Task> Tasks = new Dictionary<DatapumpTask, Task>();
public void Go()
{
Func<Task, bool> isBusy = task => task.Status == TaskStatus.Running ||
task.Status == TaskStatus.WaitingToRun ||
task.Status == TaskStatus.WaitingForActivation;
//Run Loop --- To Do move off the main thread
while (true)
{
for (int t = 0; t < Tasks.Count; t++)
{
KeyValuePair<DatapumpTask, Task> task = Tasks.ElementAt(t);
if (task.Key.NextRun < DateTime.Now && (task.Value == null || !isBusy(task.Value)))
{
Tasks[task.Key] = Task.Factory.StartNew(() => task.Key.Run());
}
if (task.Value != null && task.Value.IsFaulted)
{
task.Key.Log("Task faulted - something is wrong!" , LogType.Error);
Tasks[task.Key] = null;
}
}
}
}
}
Note DatapumpTask
has a public void Run()
method, a public void Log()
method that logs to a text file and Run()
will set its DateTime NextRun
property correctly...