I have a class that handles some hardware. I want this class to check some state of the hardware every N milleseconds, and fire an event if a certain case is true.
I would like the interface on the outside to be such:
var rack = new Rack();
rack.ButtonPushed += OnButtonPushed;
rack.Initialise();
I want to avoid using "real" threads, but I don't seem to get the Task
correctly (for testing, I just fire the event every second):
class Rack {
public event EventHandler ButtonPushed;
public void Initialise()
{
Task.Run(() =>
{
while (true)
{
Task.Delay(1000);
ButtonPushed?.Invoke(this, null);
}
});
}
}
But this doesn't work, the events get fired all at the same time.
Is Task
the right thing to use here, or should I work with a Timer, or a thread?