This may be one of the rare cases when a method async voidmay be convenient:
static async void StartAndMonitorAsync(Func<Task> taskFunc)
{
while (true)
{
var task = taskFunc();
try
{
await task;
return;
}
catch (Exception ex)
{
System.Console.WriteLine("Error: {0}, restarting...", ex.Message);
}
}
}
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)));
}
async/await, Task.ContinueWith.
startLoops ( " " ), StartAndMonitorAsync , , CancelltionToken ( " " .