Can the Expired System.Timers.Timer Callback Be Asynchronous?

Is it possible (or even sensible) to make a callback to the System.Timers.Timer method asynchronously? Sort of:

 var timer = new System.Timers.Timer { Interval = TimeSpan.FromSeconds(30).TotalMilliseconds, AutoReset = true }; timer.Elapsed += async (sender, e) => { /* await something */ }; timer.Start(); 

It compiles (obviously a good place to start), but I'm not sure I understand the consequences. Will the await timer be a callback until the timer is reset?

+5
source share
2 answers

Will the await timer be a callback until the timer is reset?

Not. Nothing can be expected there, because the signature of ElapsedEventHandler is of return type void.

In other words, your code is equivalent to:

 var timer = new System.Timers.Timer { ... }; timer.Elapsed += Foo; timer.Start(); ... private async void Foo() { ... } 

Whether this is acceptable to you or not will depend on your context. In general, the presence of asynchronous methods or anonymous functions complicates their testing and reuse, but the ability has been specifically indicated for event handlers ... You must consider how errors will be propagated.

+15
source

The title of the question is specifically about timers, but if we look at it like "How to call the asynchronous programming method after a while?" then you can do this without using a timer.

 var task2 = Task.Run(async () => { while (true) { try { await MyMethod2(); } catch { //super easy error handling } await Task.Delay(TimeSpan.FromSeconds(5)); } }); ... public async Task MyMethod2() { //async work here } 

Please note that this will have a different time (the timer will be called at intervals, the code above will be called each (runtime + sleep_time), but even if MyMethod2 takes a lot of time, it cannot be called twice. Having said that, you can calculate how long does it take to run "every x minutes".

+1
source

Source: https://habr.com/ru/post/1212026/


All Articles