如何使用线程或计时器从 WPF 客户端应用程序定期执行方法 [英] How to execute a method periodically from WPF client application using threading or timer

查看:28
本文介绍了如何使用线程或计时器从 WPF 客户端应用程序定期执行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 WPF 客户端应用程序.这个应用程序会定期向 webservice 发送数据.当用户登录应用程序时,我希望每 5 米运行一次特定方法以将数据发送到 .asmx 服务.

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.

我的问题是我是否需要使用线程或计时器.该方法应该在用户与应用程序交互时执行.即在此方法执行期间不阻塞 UI

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

有什么要找的资源吗?

推荐答案

我会推荐使用新的 async/await 关键字的 System.Threading.Tasks 命名空间.

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
}

这篇关于如何使用线程或计时器从 WPF 客户端应用程序定期执行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆