I have a timer in a Windows Service, and there is a call made to an async method inside the timer_Elapsed event handler:
protected override void OnStart(string[] args)
{
timer.Start();
}
private async void timer_Elapsed(object sender, ElapsedEventArgs e)
{
_timer.Stop();
await DoSomething();
_timer.Start();
}
Is the above code ok? Firstly, I have read that async void is not a good idea. Secondly, why would I need the timer_Elapsed method to be async in the first place? It's not like the elapsed event handler us going to get called in parallel by multiple callers. However, if I don't make the method async, then my logic will break because timer will start before DoSomething completes.
So, is making timer_Elapsed async the correct approach?
NET events do not support async Task as a result type! Instead, you have to cast event handlers as async void if you want to run async code inside of an event handler method and to comply with the classic .
You can register both synchronous and asynchronous event handlers concurrently to the same event. The Event Manager framework executes the registered event handlers in whichever mode you configure them to operate, always executing synchronous event handlers first.
The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.
The await keyword is used in an async function to ensure that all promises returned in the async function are synchronized, ie. they wait for each other. Await eliminates the use of callbacks in .
Async void should be avoided; it should only be used for event handlers. Timer.Elapsed
is an event handler. So, it's not necessarily wrong here.
The timer_Elapsed
method has to be async
because it contains an await
. This is the way the keywords work: async
rewrites the method as an asynchronous state machine, which enables the await
keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With