[英]winphone let code wait for 2 seconds DispatcherTimer
我使用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
}
這種設計並不是那么好,但它應該讓您清楚地了解多線程的工作原理。 如果你沒有做某事 ,那就不要阻止 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.