How to execute a method periodically from WPF client application using threading or timer [closed]

I would recommend the System.Threading.Tasks namespace using the new async/await keywords.

// The `onTick` method will be called periodically unless cancelled.
private static async Task RunPeriodicAsync(Action onTick,
                                           TimeSpan dueTime, 
                                           TimeSpan interval, 
                                           CancellationToken token)
{
  // Initial wait time before we begin the periodic loop.
  if(dueTime > TimeSpan.Zero)
    await Task.Delay(dueTime, token);

  // Repeat this loop until cancelled.
  while(!token.IsCancellationRequested)
  {
    // Call our onTick function.
    onTick?.Invoke();

    // Wait to repeat again.
    if(interval > TimeSpan.Zero)
      await Task.Delay(interval, token);       
  }
}

Then you would just call this method somewhere:

private void Initialize()
{
  var dueTime = TimeSpan.FromSeconds(5);
  var interval = TimeSpan.FromSeconds(5);

  // TODO: Add a CancellationTokenSource and supply the token here instead of None.
  RunPeriodicAsync(OnTick, dueTime, interval, CancellationToken.None);
}

private void OnTick()
{
  // TODO: Your code here
}

Leave a Comment