2014-11-07 2 views
1

Tick 콜백 이벤트 함수에서 Stop()으로 전화를 걸지만 멈추지 않고 계속 반복 실행합니다. 왜 그런데 어떻게 해결할 수 있습니까?타이머가 절대 멈추지 않습니다.

이 기능은 한 번만 호출됩니다

System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer(); 
void foo() { 
    timer1.Interval = 1000; 
    timer1.Tick += new EventHandler(timerTick); 
    timer1.Start(); 
} 

및 콜백 함수 : 이것은 한 번에 표시해야합니다 동안 stop it 메시지 박스의 무한대를 표시하는 것입니다

void timerTick(object o, EventArgs ea) 
{ 
    if (browser.ReadyState == WebBrowserReadyState.Complete) 
    { 
     MessageBox.Show("stop it!"); 
     timer1.Stop(); 
    } 
} 

.

+0

메시지 상자를 닫을 때까지 남은 기간은 얼마나됩니까? – BradleyDotNET

+0

메시지 상자 앞에'timer1.Stop();'을 넣으십시오. – hatchet

답변

6

당신은 당신의 문 반전해야 약자로

if (browser.ReadyState == WebBrowserReadyState.Complete) 
{ 
    timer1.Stop(); 
    MessageBox.Show("stop it!"); 
} 

을; (MessageBox.Show 블록 이후) 상자를 닫을 때까지 똑같이 똑딱 거리며, 틱의 일 수 있습니다.

1

다른 방법으로는 System.Timers.Timer을 대신 사용하십시오. 타이머가 한 번 실행되고 다시 시작될 때까지 다시 시작하지 않도록 설정할 수 있습니다.

System.Timers.Timer timer1 = new System.Timers.Timer(); 
void foo() {  
    timer1.Interval = 1000; 
    timer1.Elapsed += new ElapsedEventHandler(timerTick); 

    //This assumes that the class `foo` is in is a System.Forms class. Makes the callback happen on the UI thread. 
    timer1.SynchronizingObject = this; 

    //Tells it to not restart when it finishes. 
    timer1.AutoReset = false; 

    timer1.Start(); 
} 

void timerTick(object o, ElapsedEventArgs ea) 
{ 
    if (browser.ReadyState == WebBrowserReadyState.Complete) 
    { 
     MessageBox.Show("stop it!"); 
    } 
} 
관련 문제