28

I figured out how to use a repeat a normal method with a timer, and it worked fine. But now I have to use some async methods inside of this method, so I had to make it a Task instead of a normal method. This is the code I currently have now:

public async Task Test()
{
    Timer t = new Timer(5000);
    t.AutoReset = true;
    t.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    t.Start();
}

private async Task OnTimedEvent(Object source, ElapsedEventArgs e)
{

}

I am currently getting an error on the t.Elapsed += line because there is no await, but if I add it, it simply acts as if it was a normal func, and gives me a missing params error. How would I use this same Timer but with an async task?

John Landon
  • 345
  • 1
  • 3
  • 10
  • 5
    `OnTimedEvent` is an event handler. That is one exception where `async void` is allowed. change the method to `async void` and await your async tasks within. The `Test` method however is not async. – Nkosi Mar 09 '17 at 02:36
  • 2
    See also [the 1200+](https://stackoverflow.com/search?q=%5Bc%23%5D+async+event+handler) other related questions that already address this scenario. – Peter Duniho Mar 09 '17 at 07:36

1 Answers1

59

For event handlers you can go ahead and use async void return type. Your code should look like this:

public void Test()
{
    Timer t = new Timer(5000);
    t.AutoReset = true;
    t.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    t.Start();
}

private async void OnTimedEvent(Object source, ElapsedEventArgs e)
{

}
Neuron
  • 5,141
  • 5
  • 38
  • 59
Mike Hixson
  • 5,071
  • 1
  • 19
  • 24
  • By the way there is a small mistake here as the delegate function ElapsedEventHandler actually looks like this: `public delegate void ElapsedEventHandler(object? sender, ElapsedEventArgs e);` So you should change your OnTimedEvent to be: `OnTimedEvent(object? sender, ElapsedEventArgs e)` – nights Mar 02 '23 at 10:36
  • Which timer is this using? Please specify the namespace for this timer. – Zapnologica Aug 11 '23 at 17:26
  • looking at the signature @zapnologica I would expect System.Timers.Timer – Brett Styles Aug 14 '23 at 06:43