Task.Delay takes too long on macOS
See original GitHub issueDescribe the bug In an Avalonia macOS desktop app Task.Delay often takes too long to return. In a simple non-Avalonia console app the issue does not occur.
To Reproduce Steps to reproduce the behavior:
- Create a minimal Avalonia app from the VS project template.
- Somewhere (e.g. MainWindow) put Task.Delay in an infinite loop.
- Often Task.Delay takes way longer than configured.
Expected behavior Task.Delay takes about as long as configured.
Desktop (please complete the following information):
- OS: Mac
- Version: 12.5
Additional context Repro: https://github.com/Stannieman/AvaloniaDelayTest This loops a Task.Delay of 250ms. When delay takes longer than 500ms it prints the actual duration to the terminal.
After only a couple of minutes the output looks like this:
Too long: 00:00:10.1278680
Too long: 00:00:01.4919020
Too long: 00:00:10.1362750
Too long: 00:00:10.0013450
Too long: 00:00:10.0012170
Too long: 00:00:10.0014200
Too long: 00:00:10.0012190
Too long: 00:00:10.0014000
Too long: 00:00:10.0014770
Too long: 00:00:10.0012340
Too long: 00:00:10.0298920
Too long: 00:00:09.9944410
Too long: 00:00:10.0013260
Too long: 00:00:10.0011620
Too long: 00:00:10.0011870
Too long: 00:00:10.0100230
Too long: 00:00:10.0057740
Too long: 00:00:10.0125380
Too long: 00:00:10.0072980
Too long: 00:00:10.0296070
Too long: 00:00:09.9992390
Too long: 00:00:10.0023670
Too long: 00:00:10.0020110
Too long: 00:00:10.0019850
Too long: 00:00:10.0063740
Too long: 00:00:09.9987900
Too long: 00:00:10.0016140
Too long: 00:00:01.4810180
Too long: 00:00:10.0016090
Too long: 00:00:20.0312540
Too long: 00:00:19.9925110
Too long: 00:00:20.0018100
Too long: 00:00:20.0017170
Too long: 00:00:20.0116750
Too long: 00:00:19.9987460
Too long: 00:00:20.0019690
Too long: 00:00:20.0016450
Too long: 00:00:20.0018110
Too long: 00:00:03.6547710
Too long: 00:00:02.4756200
Too long: 00:00:02.5731120
Too long: 00:00:03.6644760
Since Task.Delay behind the scenes uses the same timer mechanism as most if not all other .NET timer APIs this is quite concerning.
Is Avalonia messing with doing something thread pool/scheduling stuff somewhere? The machine is idle when this occurs. Memory is not full, no CPU spikes. It just “happens”.
Issue Analytics
- State:
- Created a year ago
- Comments:18 (5 by maintainers)
Top GitHub Comments
@maxkatz6 seems you are right. After running
defaults write NSGlobalDomain NSAppSleepDisabled -bool YES
to disable App Nap globally the issue is completely gone. Thanks! So yep, we need to look at some PInvoke magic.Created a PR with new option,
but the app crashes when loading. Any ideas? My C++ is decent but I do not see what is going wrong here.Today it magically works 🤷 I got 1 open question https://github.com/AvaloniaUI/Avalonia/pull/8894#discussion_r962748576 when this is resolved it is ready for review.