首页 文章

UWP相当于Timer.Elapsed事件

提问于
浏览
7

我需要每隔几分钟自动发起一次事件 . 我知道我可以使用Windows Forms应用程序中的Timers.Elapsed事件执行此操作,如下所示 .

using System.Timers;

namespace TimersDemo
{
    public class Foo
    {
        System.Timers.Timer myTimer = new System.Timers.Timer();

        public void StartTimers()
        {                
            myTimer.Interval = 1;
            myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
            myTimer.Start();
        }

        void myTimer_Elapsed(object sender, EventArgs e)
        {
            myTimer.Stop();
            //Execute your repeating task here
            myTimer.Start();
        }
    }
}

我已经google了很多,并努力在UWP中找到相同的东西 .

2 回答

  • 10

    以下使用DispatcherTimer的代码段应提供等效功能,该功能在UI线程上运行回调 .

    using Windows.UI.Xaml;
    public class Foo
    {
        DispatcherTimer dispatcherTimer;
        public void StartTimers()
        {
            dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
        }
    
        // callback runs on UI thread
        void dispatcherTimer_Tick(object sender, object e)
        {
            // execute repeating task here
        }
    }
    

    当没有必要在UI线程上更新而你只需要一个计时器时,你可以使用ThreadPoolTimer,就像这样

    using Windows.System.Threading;
    public class Foo
    {
        ThreadPoolTimer timer;
    
        public void StartTimers()
        {
            timer = ThreadPoolTimer.CreatePeriodicTimer(TimerElapsedHandler, new TimeSpan(0, 0, 1));
        }
    
        private void TimerElapsedHandler(ThreadPoolTimer timer)
        {
            // execute repeating task here
        }
    }
    
  • 3

    最近我解决了类似的任务,当我在UWP应用程序中需要定期计时器事件时 .

    即使您使用ThreadPoolTimer,您仍然可以从timer事件处理程序对UI进行非阻塞调用 . 它可以通过使用Dispatcher对象并调用其RunAsync方法来实现,如下所示:

    TimeSpan period = TimeSpan.FromSeconds(60);
    
    ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((source) =>
    {
        // 
        // TODO: Work
        // 
    
        // 
        // Update the UI thread by using the UI core dispatcher.
        // 
        Dispatcher.RunAsync(CoreDispatcherPriority.High,
            () =>
            {
                // 
                // UI components can be accessed within this scope.
                // 
    
            });
    
    }, period);
    

    代码段取自本文:Create a periodic work item .

    我希望它会有所帮助 .

相关问题