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

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 11:44:05

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
}

You need to use Timer class. There are multiple built-in timers and it depends on the requirement which timer to use.

  1. System.Timers.Timer: This is more suitable for mutlithreaded access. Instances of this timer are threadsafe.

  2. System.Threading.Timer : Instances of this timer are not thread safe.

  3. System.Windows.Threading.DispatcherTimer -> It sends event to Dispatcher thread (and is not multithreaded). This is useful if you need to update UI.

  4. System.Windows.Forms.Timer -> This timer raises events in UI thread. This is optimized for windows forms, and not to be used in WPF.

Following is an interesting read.
Comparing the Timer Classes in the .NET Framework Class Library

If you want the method to execute on a different thread than the UI one, use System.Threading.Timer. Otherwise (but I don't think it's your case), use System.Windows.Threading.DispatcherTimer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!