I'm using System.Threading.Timer
to run some things that are async
It means my callbacks are async void
.
private async void CallbackAsync(object state) {
_timer.Change(Timeout.Infinite, Timeout.Infinite);
await SomethingAsync();
_timer.Change(TimeToNextCallback, Timeout.Inifinite);
}
With non async callbacks I have used code like this to shut down the timer safely.
using (var waitHandle = new AutoResetEvent(false)) {
if (_timer.Dispose(waitHandle)) {
waitHandle.WaitOne();
}
}
My understanding is that this will not work with async callbacks. The callback will return on the first await
and the Timer is unaware of scheduled continations. I.e the code above might return before the continuations has completed (and the callback might try to change a disposed timer).
First, is my understanding correct?
Second, what is the correct way to wait for async callbacks to finish?