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

后端 未结 3 1754
灰色年华
灰色年华 2020-12-10 12:06

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

3条回答
  •  猫巷女王i
    2020-12-10 12:35

    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.

提交回复
热议问题