Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an async task inside a timer? [duplicate]

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?

like image 284
John Landon Avatar asked Mar 09 '17 02:03

John Landon


1 Answers

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)
{

}
like image 197
Mike Hixson Avatar answered Sep 26 '22 08:09

Mike Hixson