在给定的延迟后执行方法的简单方法?
有没有一种简单的方法可以在给定的延迟后执行一个方法,就像 iOS 中开箱即用的那样?
在 iPhone 上,我会这样做:
[self PerformSelector:@selector(connectSensor) withObject:nil afterDelay:2.5];
然后它将在主线程上安排方法 connectSensor
( UI 线程)在 2.5 秒后执行。而且由于它是自动调度在主线程上的,所以你不必担心跨线程问题。 (还有一个 performSelectorOnBackground
版本)
那么我如何在 WP7 中正确执行此操作?
目前我正在使用计时器来完成此操作,但我不确定这是否有效是一个很好的解决方案。
private Timer timer;
private void DoSomethingAfterDaly()
{
// ... do something here
timer = new Timer( (o) => Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.GoBack()), null, 2500, Timeout.Infinite);
}
如何将其封装到扩展方法中,以便我可以调用 this.Perform(MyMethod, null, 2500);
?
Is there a easy way to perform a method after a given delay like in iOS out of the box?
On iPhone I would do this:
[self performSelector:@selector(connectSensor) withObject:nil afterDelay:2.5];
It will then schedule the method connectSensor
on the main thread (UI thread) to be executed after 2,5 seconds. And because it is automatically scheduled on the main thread, you don't have to worry about cross thread issues. (There is also a performSelectorOnBackground
version)
So how would I do this properly in WP7?
Currently I'm accomplishing this with a timer, but I'm not sure if this is a good solution.
private Timer timer;
private void DoSomethingAfterDaly()
{
// ... do something here
timer = new Timer( (o) => Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.GoBack()), null, 2500, Timeout.Infinite);
}
How could this be encapsulated into an extension method so I can just call this.Perform(MyMethod, null, 2500);
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像这样使用BackgroundWorker:
对此方法的调用如下所示:
后台工作程序将在UI线程之外的线程上运行睡眠,以便您的应用程序在发生延迟时可以自由地执行其他操作。
You can use a BackgroundWorker like so:
The call into this method would look like this:
The background worker will run the sleep on a thread off of the UI thread so your application is free to do other things while the delay is occurring.
您可以使用 WP7 的反应式扩展来观察计时器:
鉴于此代码的简洁性,我认为通过为其创建扩展方法不会获得太多好处:) 有关 WP7 反应式扩展的更多信息,请查看此 MSDN 页面
。
You can use the Reactive Extensions for WP7 to observe on a timer:
Given the brevity of this code, I don't think you'd gain much by creating an extension method for it :) For more information about the Reactive Extensions for WP7, take a look at this MSDN page
.