0

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?

11
  • 6
    Shouldn't you be e.g. awaiting for that Task.Delay() to complete..? See the Example for learn.microsoft.com/en-us/dotnet/api/…
    – AKX
    Jul 29, 2021 at 10:47
  • 6
    "I want this class to check some state of the hardware every N milleseconds, and fire an event if a certain case is true" Maybe use Timer then?
    – Guru Stron
    Jul 29, 2021 at 10:55
  • When you have added async to the Task, you should probably provide means to cancel this Task. A default CancellationToken may do (plus a public method added to the Rack class).
    – Jimi
    Jul 29, 2021 at 10:56
  • 1
    I second Guru. Task is not the tool of choice. Either a Timer or a Scheduling Framework is.
    – Fildor
    Jul 29, 2021 at 10:56
  • 1
    @GuruStron that was my mistake. I had two instances running; one of them didn't register an event handler. Jul 29, 2021 at 11:50

1 Answer 1

3

Task delay returns a task that finishes execution after given time and needs to be awaited. In order to await it we'd need to mark the delegate as async and add await before the call:

class Rack {
  public event EventHandler ButtonPushed;
  public void Initialise()
  {
    Task.Run(async () =>
    {
        while (true)
        {
            await Task.Delay(1000);
            ButtonPushed?.Invoke(this, null);
        }
    });
  }
}

Is Task the right thing to use here, or should I work with a Timer, or a thread?

Well, your approach is just as good as using Timer. Thread could be used as well but it's a bit too low-level approach.

As others mentioned it would be better with CancellationToken, this allows us to cancel the task later so it finishes execution:

while (!cancellationToken.IsCancellationRequested)
{
   ...
}
8
  • Most likely it happens because of a different thread context. We attach handler in one thread but fire events in another thread
    – Fabjan
    Jul 29, 2021 at 11:07
  • To answer that we need more details. Is it a console app or an app with GUI ? Which version of .NET Framework/Core did you use ?
    – Fabjan
    Jul 29, 2021 at 11:11
  • I don't think there's any reason for the event handler to remain null if you follow the answer
    – asaf92
    Jul 29, 2021 at 11:12
  • Sorry I meant SynchronizationContext not ThreadContext
    – Fabjan
    Jul 29, 2021 at 11:39
  • This works, but when I update a TextBox.Text property in the event handler, it seems to hang. I guess this is some kind of threading issue? It is a WinForms application BTW, .NET Framework 4.7.2 Jul 29, 2021 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.