Skip to content

Instantly share code, notes, and snippets.

@theodorzoulias
Last active November 2, 2025 04:26
Show Gist options
  • Select an option

  • Save theodorzoulias/2cd5cc743850634da9576cb7c56ea377 to your computer and use it in GitHub Desktop.

Select an option

Save theodorzoulias/2cd5cc743850634da9576cb7c56ea377 to your computer and use it in GitHub Desktop.
Custom DispatcherTimer-based Delay for WPF applications
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