9

我需要每隔几分钟自动触发一个事件。我知道我可以在 Windows 窗体应用程序中使用 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();
        }
    }
}

我用谷歌搜索了很多,并努力在 UWP 中找到与此等效的内容。

4

2 回答 2

12

以下使用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
    }
}
于 2016-12-08T07:16:37.560 回答
2

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

即使您使用 ThreadPoolTimer,您仍然可以从计时器事件处理程序对 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);

代码片段摘自这篇文章:创建周期性工作项

我希望它会有所帮助。

于 2016-12-09T16:31:02.613 回答