• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

180
Views
How to call an async task inside a timer?

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?

about 3 years ago · Santiago Trujillo
1 answers
Answer question

0

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

}
about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error