C# winphone让代码等待2秒Dispatcher
我正在使用VisualStudio2010为Win Phone进行图像处理。 为了让图片显示2秒钟(如幻灯片放映),调用以下类C# winphone让代码等待2秒Dispatcher,c#,windows-phone-7,timer,C#,Windows Phone 7,Timer,我正在使用VisualStudio2010为Win Phone进行图像处理。 为了让图片显示2秒钟(如幻灯片放映),调用以下类 namespace photoBar { public class WaitTwoSeconds { DispatcherTimer timer = new DispatcherTimer(); public bool timeUp = false; // This is the method to ru
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)
{
}
因为应用程序.DoEvents()代码>声明为错误:“System.Windows.Application”不包含“DoEvents”的定义。所以我删除了那个代码块
while (timeUp== false)
{
// Processes all the events in the queue.
Application.DoEvents();
}
编译并运行程序后,显示resume…
我怎样才能纠正这个问题?谢谢使用响应式扩展可以更轻松地完成此操作(参考Microsoft.Phone.Reactive):
请注意,代码不会在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
}
这种设计不是很好,但它应该让您清楚地了解多线程是如何工作的。如果你没有做什么,那么不要阻止,从长远来看,这实际上是一条比我更好的路线。不要害怕框架。
private WaitTwoSeconds waitTimer;
private void SomeButtonHandlerOrSomething(
object sender, ButtonClickedEventArgsLol e)
{
waitTimer = new WaitTwoSeconds(AfterTwoSeconds);
}
private void AfterTwoSeconds()
{
// do whatever
}