我需要每隔几分钟自动启动一个事件。我知道我可以在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中找到与之相当的内容。
发布于 2016-12-08 07:16:37
下面使用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-09 16:31:02
最近,我解决了类似的任务,当我需要周期性的时间事件在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);代码片段摘自本文:创建一个定期工作项。
我希望这会有所帮助。
https://stackoverflow.com/questions/41033783
复制相似问题