Miquel
Miquel

Reputation: 15675

How to best implement a watchdog on a neverending task in C#?

I've got a service which, at its core, runs a few neverending loops by calling methods like:

public async Task DoStuffPeriodically(CancellationToken token);

They are invoked by calling:

var tokenSource = new CancellationTokenSource();
var stuffTask = DoStuffPeriodically(tokenSource.token);

Now, this will run forever, and only get stopped when, on a different method, we cancel the token and call stuffTask.Wait(). Only then do we get any exceptions that DoStuffPeriodically might have trown.

It is possible (but unlikely) that DoStuffPeriodically actually throws, which means the loop I'm counting on is no longer running. I was planning on monitoring it by having a loop in the main thread that periodically checks stuffTask.IsFaulted and throws an exception (which will force the service to reboot).

Is there a better way to do this? I wouldn't like to poll the Task state if there's anyway to get a callback from it that I'm unaware of.

Thanks!

Upvotes: 2

Views: 1444

Answers (1)

Kapol
Kapol

Reputation: 6463

You can use Task.ContinueWith, passing TaskContinuationOptions.OnlyOnFaulted to the continuationOptions parameter. This will trigger the callback only when the antecedent threw an unhandled exception. In this callback you can set some flag or throw an exception.

stuffTask.ContinueWith(t => { throw new Exception(); },
    null, 
    TaskContinuationOptions.OnlyOnFaulted);

Upvotes: 4

Related Questions