未链接到UI的UWP App中的计时器 [英] Timer in UWP App which isn't linked to the UI
问题描述
我正在研究UWP MVVM项目,如果用户交互在特定时间内停止,我想实现一个自动注销系统。
到目前为止,我使用的是 DispatcherTimer
从每秒200开始倒数。
I'm working on an UWP MVVM project and would like to implement an automatic logout system if the user interaction stops for a specific time.
Until now I'm using a DispatcherTimer
to count backwards from 200 every second.
TimerLeave = 200;
var _dispatcherTimer = new DispatcherTimer();
_dispatcherTimer.Tick += dispatcherTimer_Tick;
_dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
_dispatcherTimer.Start();
但是由于DispatcherTimer与UI链接了
,因此我正在构建MVVM应用程序,我正在寻找替代方法。
我进行了一些搜索,发现在计时器上运行后台任务。问题是
只能将此计时器设置为每15分钟运行一次,对于我而言,这太长了,无法自动注销用户。我找不到减少15分钟的解决方法。
所以我的问题是,是否有可能在未链接到UI且可以设置变量的UWP项目中设置计时器? / p>
But because the DispatcherTimer is linked
with the UI and I'm building a MVVM App, I'm looking for an alternative.
I searched a bit and found Run a background task on a timer. The problem is
that this timer can only be set to run every 15 minutes, which is a little too long to automaticly logout a user in my case. I found no workaround to reduce the 15 minutes.
So my question is, is there any possibility to set up a timer in an UWP Project that isn't linked to the UI and can be set variable?
推荐答案
是-例如,您可以使用计时器类-尽管您必须记住它在单独的线程上运行。示例:
Yes - you can for example use Timer class - though you must remember that it run on separate thread. Example:
private Timer timer;
public MainPage()
{
this.InitializeComponent();
timer = new Timer(timerCallback, null, (int)TimeSpan.FromMinutes(1).TotalMilliseconds, Timeout.Infinite);
}
private async void timerCallback(object state)
{
// do some work not connected with UI
await Window.Current.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() => {
// do some work on UI here;
});
}
请注意,可能不会立即处理在UI调度程序上调度的工作-它
Note that the work dispatched on UI dispatcher may not be processed right away - it depend on dispatcher's workload.
还要记住,此计时器与您的应用程序一起运行,并且在应用程序暂停时将不起作用。
Also remember that this timer runs along with your app and won't work when app is suspended.
这篇关于未链接到UI的UWP App中的计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!