I wish to execute a function at an interval of 1 or so minutes. How can I achieve this in Windows Phone 8.
I am not looking for background agents. The app will be running in the foreground. What are my options?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
you can use the DispatcherTimer Class
private DispatcherTimer dispatcherTimer;
// Constructor
public MainPage()
{
InitializeComponent();
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
//do whatever you want to do here
}
Refer: (http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer(v=vs.110).aspx)
回答2:
Try this
public void Start_timer()
{
DispatcherTimer timer = new DispatcherTimer();
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(00, 0, 10);
bool enabled = timer.IsEnabled;
timer.Start();
}
void timer_Tick(object sender, object e)
{
//function to execute
}
回答3:
You can also use ThreadPoolTimer
:
TimeSpan period = TimeSpan.FromSeconds(60);
ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((source) =>
{
// TODO: Work
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// UI update
});
}, period);
回答4:
One option may be to use DispatcherTimer.
Simply register a callback on the Tick event.