问题描述
我开发一个 WPF
客户端application.This应用会定期将数据发送到 Web服务
。当用户登录到应用程序,我想运行特定方法,每5 MTS将数据发送到的.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.
我的问题是我是否需要使用线程或timer.This方法执行,同时用户与应用程序交互应该发生。
即如果没有这个方法执行期间阻塞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
任何资源寻找?
推荐答案
我会建议使用新的异步的
关键字。 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客户端应用程序使用的线程或定时执行的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!