Last active
November 2, 2025 04:26
-
-
Save theodorzoulias/2cd5cc743850634da9576cb7c56ea377 to your computer and use it in GitHub Desktop.
Custom DispatcherTimer-based Delay for WPF applications
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Threading.Tasks; | |
| using System.Windows.Threading; | |
| namespace App; | |
| static partial class Extensions | |
| { | |
| // https://stackoverflow.com/questions/79806454/task-delay-versus-custom-dispatchertimer-based-delay-in-wpf | |
| public static Task Delay(this DispatcherObject source, int millisecondsDelay) | |
| { | |
| ArgumentNullException.ThrowIfNull(source); | |
| ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsDelay, 0); | |
| TaskCompletionSource tcs = new(); | |
| DispatcherTimer timer = new(DispatcherPriority.Normal, source.Dispatcher); | |
| timer.Interval = TimeSpan.FromMilliseconds(millisecondsDelay); | |
| timer.Tick += (s, e) => { timer.Stop(); tcs.SetResult(); }; | |
| timer.Start(); | |
| return tcs.Task; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment