Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

c# - Timer in UWP App which isn't linked to the UI

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();

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
        });
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...