I am a hardware/test engineer currently writing a C# application for a device that does not have any event/interrupt mechanisms. Because of this I am forced to poll the device's internal control registers using their provided API for any change in state. I realize that a dedicated thread will be needed in order to take care of the polling.
The conceptual question that I have is, would the following design pattern (where the object representing the piece of hardware starts/ends it's own Task) be an acceptable practice for what I am trying to do?
The specific reason that I am asking this question because normally the overall control would be done at the highest level, but in this case I have to monitor an unmanaged resource and know that I have to do it at the lower level. As an alternative, I guess we could have a method called Monitor
that would be responsible for doing what TaskMethod
currently does, and just do the Task/Token from the scope that instantiates the MyConstructor
.
private readonly CancellationTokenSource myTokenSource = new CancellationTokenSource();
private CancellationToken myToken = CancellationToken.None;
private Task eventLogTask;
// default constructor
public MyConstructor
{
}
// method that starts a task
public void StartTask()
{
// start the event logger
this.eventLogTask = Task.Factory.StartNew(() =>
{
this.TaskMethod();
}, this.myToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
// cancel/wait the polling/monitoring event
public void StopTask()
{
this.myTokenSource.Cancel();
this.eventLogTask.Wait();
}
// method performed on the new task
private void TaskMethod()
{
// assign a cancellation token source
this.myToken = myTokenSource.Token;
// start monitoring the event log
while (!this.myToken.IsCancellationRequested)
{
// TODO: control monitoring code
Thread.Sleep(1);
}
}
Note: The term event log doesn't have anything to do with .NET events, but instead refers to something that behaves loosely like a micro-controller's register that needs to be polled in order to get the status of the hardware.