I would like to start an asynchronous operation with the creation of an object and for it to run at intervals for the lifetime of the object. I have one implementation of how this might be done (see code below); but would like feedback on how it might be improved upon.
An example of how I might use this class would would be an object that manages & tracks the state of some piece of hardware and needs to query its state (e.g. via serial or tcp queries) at intervals. I don't want the call/creator of the object to have to manage this.
I am trying to follow the best practices of Steven Cleary as laid out in his many articles on the subject. These would seem to indicate I should avoid the use of Task.Start and .ContinueWith for this. At the same time I want to be able to sensibly handle errors that may occur while the background task is being running.
class Worker
{
private Task _BGWork;
public Worker()
{
_BGWork = BackgroundWork();
// If i were to use ContinueWith, next would be ...
// _BGWORk.ContinueWith(HandleError, TaskContinuationOptions.OnlyOnFaulted);
}
private async Task BackgroundWork()
{
try
{
while (true)
{
// do work... update Worker state etc...
// use .ConfigureAwait(false) here when possible
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
catch (Exception) // if not using ContinueWith, can't let any errors escape as they will be silently ignored
{
HandleError();
}
}
private void HandleError()
{ // 'Fix' the glitch
}
public void Dispose()
{ // clean up the task if needed
}
Thanks for any feedback.