This might be one of the rare cases when an async void
method could be convenient:
static async void StartAndMonitorAsync(Func<Task> taskFunc)
{
while (true)
{
var task = taskFunc();
try
{
await task;
// process the result if needed
return;
}
catch (Exception ex)
{
// log the error
System.Console.WriteLine("Error: {0}, restarting...", ex.Message);
}
// do other stuff before restarting (if any)
}
}
static private void startLoops()
{
System.Console.WriteLine("Starting fizzLoop.");
StartAndMonitorAsync(() => Task.Factory.StartNew(new Action(fizzLoop)));
System.Console.WriteLine("Starting buzzLoop.");
StartAndMonitorAsync(() => Task.Factory.StartNew(new Action(buzzLoop)));
}
If you can't use async/await
, a similar logic can be implemented using Task.ContinueWith
.
If startLoops
can be called multiple times (while tasks are already "in-flight"), you'd need to add cancellation logic to StartAndMonitorAsync
and the tasks it sarts, using CancelltionToken
(more details in "A pattern for self-cancelling and restarting task").