Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using async await inside the timer_elapsed event handler within a windows service

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?

like image 487
Prabhu Avatar asked Jul 29 '14 03:07

Prabhu


People also ask

Which async method can be used for event handlers?

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 .

Can event handlers be async?

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.

How async await works internally?

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.

Can I use await for synchronous 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 .


1 Answers

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.

like image 67
Stephen Cleary Avatar answered Oct 16 '22 11:10

Stephen Cleary