如何使用线程或计时器从WPF客户端应用程序定期执行方法
我正在开发一个WPF
客户端应用程序。这个应用程序定期向webservice
发送数据。 当用户登录应用程序时,我希望每5 mts运行特定方法将数据发送到.asmx
服务。
我的问题是我是否需要使用线程或计时器。这个方法执行应该在用户与应用程序交互时发生。 即在此方法执行期间不阻止UI
要查找的资源是什么?
我推荐使用新的async/await
关键字的System.Threading.Tasks
命名空间。
// 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); } }
那你只需要在某个地方调用这个方法:
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 }
您需要使用Timer
类。 有多个内置定时器,它取决于使用哪个定时器的要求。
-
System.Timers.Timer :这更适合multithreading访问。 此计时器的实例是线程安全的。
-
System.Threading.Timer :此计时器的实例不是线程安全的。
-
System.Windows.Threading.DispatcherTimer – >它将事件发送到
Dispatcher
线程(并且不是multithreading的)。 如果您需要更新UI,这非常有用。 -
System.Windows.Forms.Timer – >此计时器在UI线程中引发事件。 这是针对Windows窗体优化的,不能在WPF中使用。
以下是一本有趣的读物。
比较.NET Framework类库中的Timer类
如果希望方法在与UI不同的线程上执行,请使用System.Threading.Timer
。 否则(但我不认为这是你的情况),使用System.Windows.Threading.DispatcherTimer
。