UWP 应用中未链接到 UI 的计时器 [英] 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 项目中设置计时器?
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.
这篇关于UWP 应用中未链接到 UI 的计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!