UWP相当于Timer.Elapsed事件

时间:2016-12-08 07:12:38

标签: c# .net uwp uwp-xaml system.timers.timer

我需要每隔几分钟自动发起一次事件。我知道我可以使用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();
        }
    }
}

我搜索了很多内容并努力在UWP中找到相同的内容。

2 个答案:

答案 0 :(得分:11)

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

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

当不需要在UI线程上更新并且您只需要一个计时器时,您可以使用ThreadPoolTimer,如此

<form method="post" action="store">

答案 1 :(得分: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

我希望它会有所帮助。

相关问题