I have an engine that has an arbitrary number of pollers which each do their "poll" every few seconds. I want the pollers to run in different threads, but each "poll" within a single poller should be sequential so that one happens after the next. Everything is working using this code to start the polling process:
public void StartPolling()
{
Stopwatch watch = new Stopwatch();
while (Engine.IsRunning)
{
Task task = Task.Factory.StartNew(() =>{
watch.Restart();
Poll();
watch.Stop();
},TaskCreationOptions.LongRunning);
task.Wait();
if(Frequency > watch.Elapsed) Thread.Sleep(Frequency - watch.Elapsed);
}
}
It took me awhile, however, to discover the TaskCreationOptions.LongRunning option which solved a strange problem I was having that I still don't understand. Without that option, if I run a test that creates 1-3 of these pollers, everything worked fine. If I created 4+ then I ran into strange behavior. Three of the pollers would work, one would just perform one poll, and any remaining would not poll at all. It makes total sense that my tasks are long running. They are after all running the entire length of my program. But I don't understand why I would get some bad behavior without this option set. Any help would be appreciated.