How to execute a method periodically from WPF clie

2019-01-10 18:05发布

问题:

I am developing a WPF client application.This app sends data periodically to the webservice. When user logged into the app I want run particular method every 5 mts to send data to the .asmx service.

My question is whether I need to use threading or timer.This method execution should happen while user is interacting with the application. i.e without blocking the UI during this method execution

Any resources to look for ?

回答1:

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
}


回答2:

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



回答3:

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.