I am looking for the correct way/structure to create a loop in a Thread/Task
...
The reason for this is, i need to check the DB every 15sec for report re
I've made a work-around starting from @Roger's answer. (A friend of mine has given good advices regarding this too)... I copy it here I guess it could be useful:
///
/// Recurrent Cancellable Task
///
public static class RecurrentCancellableTask
{
///
/// Starts a new task in a recurrent manner repeating it according to the polling interval.
/// Whoever use this method should protect himself by surrounding critical code in the task
/// in a Try-Catch block.
///
/// The action.
/// The poll interval.
/// The token.
/// The task creation options
public static void StartNew(Action action,
TimeSpan pollInterval,
CancellationToken token,
TaskCreationOptions taskCreationOptions = TaskCreationOptions.None)
{
Task.Factory.StartNew(
() =>
{
do
{
try
{
action();
if (token.WaitHandle.WaitOne(pollInterval)) break;
}
catch
{
return;
}
}
while (true);
},
token,
taskCreationOptions,
TaskScheduler.Default);
}
}