如何使用线程或计时器从WPF客户端应用程序定期执行方法

ums*_*esh 11 c# wpf multithreading client-applications timer

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

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

有资源寻找吗?

Eri*_*rik 30

我建议System.Threading.Tasks使用新async/await关键字命名空间.

// 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);       
  }
}
Run Code Online (Sandbox Code Playgroud)

那你只需要在某个地方调用这个方法:

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
}
Run Code Online (Sandbox Code Playgroud)


Til*_*lak 10

你需要使用Timer课程.有多个内置定时器,它取决于使用哪个定时器的要求.

  1. System.Timers.Timer:这更适合多线程访问.此计时器的实例是线程安全的.

  2. System.Threading.Timer:此计时器的实例不是线程安全的.

  3. System.Windows.Threading.DispatcherTimer - >它将事件发送到Dispatcher线程(并且不是多线程的).如果您需要更新UI,这非常有用.

  4. System.Windows.Forms.Timer - >此计时器在UI线程中引发事件.这是针对Windows窗体优化的,不能在WPF中使用.

以下是一本有趣的读物.
比较.NET Framework类库中的Timer类


Mir*_*Mir 2

如果您希望该方法在与 UI 线程不同的线程上执行,请使用System.Threading.Timer. 否则(但我不认为这是你的情况),请使用System.Windows.Threading.DispatcherTimer.