Categories
Tips and Tricks

C# WPF run a function every second

To run a function every second use the DispatcherTimer Class

https://docs.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatchertimer?redirectedfrom=MSDN&view=netframework-4.8

//  DispatcherTimer setup
DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    // This will tricker every second
}

DispatcherTimer will tick evey second calling dispatcherTimer_Tick. You can set the interval with a timespan