winphone让代码等待2秒DispatcherTimer
本文关键字:2秒 DispatcherTimer 等待 代码 winphone | 更新日期: 2023-09-27 17:58:19
我正在使用visual studio 2010为Win Phone进行图像处理。为了让图片显示2秒(就像幻灯片一样),下面的类被称为
namespace photoBar
{
public class WaitTwoSeconds
{
DispatcherTimer timer = new DispatcherTimer();
public bool timeUp = false;
// This is the method to run when the timer is raised.
private void TimerEventProcessor(Object myObject,
EventArgs myEventArgs)
{
timer.Stop();
timeUp = true;
}
public WaitTwoSeconds()
{
/* Adds the event and the event handler for the method that will
process the timer event to the timer. */
timer.Tick += new EventHandler(TimerEventProcessor);
// Sets the timer interval to 2 seconds.
timer.Interval = new TimeSpan(0, 0, 2); // one second
timer.Start();
//// Runs the timer, and raises the event.
while (timeUp== false)
{
// Processes all the events in the queue.
Application.DoEvents();
}
}
}
}
它是这样命名的:
WaitTwoSeconds waitTimer = new WaitTwoSeconds();
while (!waitTimer.timeUp)
{
}
因为Application.DoEvents();
被声明为错误:"System.Windows.Application"不包含"DoEvents"的定义。所以我删除了代码块
while (timeUp== false)
{
// Processes all the events in the queue.
Application.DoEvents();
}
编译并运行程序后,会显示简历
我该如何更正?感谢
使用Reactive Extensions(参考Microsoft.Phone.Reactive):可以更容易地做到这一点
Observable.Timer(TimeSpan.FromSeconds(2)).Subscribe(_=>{
//code to be executed after two seconds
});
请注意,代码不会在UI线程上执行,因此您可能需要使用Dispatcher。
拥抱多线程。
public class WaitTwoSeconds
{
DispatcherTimer timer = new DispatcherTimer();
Action _onComplete;
// This is the method to run when the timer is raised.
private void TimerEventProcessor(Object myObject,
EventArgs myEventArgs)
{
timer.Stop();
_onComplete();
}
public WaitTwoSeconds(Action onComplete)
{
_onComplete = onComplete;
timer.Tick += new EventHandler(TimerEventProcessor);
timer.Interval = new TimeSpan(0, 0, 2); // one second
timer.Start();
}
}
在你的代码中
private WaitTwoSeconds waitTimer;
private void SomeButtonHandlerOrSomething(
object sender, ButtonClickedEventArgsLol e)
{
waitTimer = new WaitTwoSeconds(AfterTwoSeconds);
}
private void AfterTwoSeconds()
{
// do whatever
}
这个设计不是很好,但它应该让你清楚地了解多线程是如何工作的。如果你没有做的事情,那么不要阻止。