2016-01-22 67 views
1

我环顾了很多,并找到了一些答案,但没有一个工作。定时器作为睡眠?

据我所知,“睡眠()”冻结了应用程序,这就是为什么我添加了一个计时器。我想这样我这样做是它睡觉1000毫秒:

Timer1.Interval = 1000 
Timer1.Start() 

然而,这似乎并没有工作。我没有得到任何错误,程序运行就像它没有计时器时的运行。

我正在做这个对吗?如果不是,有人可以修复它? (定时器启用)

谢谢!

+1

'Timer1'将每1000ms触发一个事件;他们不睡觉。在环顾四周时,你一定错过了这个:[Timer Class](https://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v = vs.110).aspx) – Plutonix

+0

All you所做的就是启动计时器。您的代码将继续执行'Timer1.Start()'后面的指令。您需要退出此方法,然后在'Timer1.Tick'事件中,您可以执行重新处理所需的操作。 – Blackwood

+1

我想你可能想要的是'等待Task.Delay(1000)' – Crowcoder

回答

0

你需要听Tick事件https://msdn.microsoft.com/en-us/library/system.windows.forms.timer.tick(v=vs.90).aspx

创建一个处理程序,并跟踪蜱有:

'prompts the user whether the timer should continue to run' 
Private Shared Sub TimerEventProcessor(ByVal myObject As Object, _ 
             ByVal myEventArgs As EventArgs) _ 
            Handles myTimer.Tick 
    myTimer.Stop() 

    ' Displays a message box asking whether to continue running the timer. 
    If MessageBox.Show("Continue running?", "Count is: " & alarmCounter, _ 
         MessageBoxButtons.YesNo) = DialogResult.Yes Then 
     ' Restarts the timer and increments the counter. 
     alarmCounter += 1 
     myTimer.Enabled = True 
    Else 
     ' Stops the timer. 
     exitFlag = True 
    End If 
End Sub 

,并在主

Public Shared Sub Main() 
    ' Adds the event and the event handler for the method that will 
    ' process the timer event to the timer. 

    ' Sets the timer interval to 5 seconds. 
    myTimer.Interval = 5000 
    myTimer.Start() 

    ' Runs the timer, and raises the event. 
    While exitFlag = False 
     ' Processes all the events in the queue. 
     Application.DoEvents() 
    End While 

End Sub 

希望这有助于。

+0

我知道这很容易转换为VB,但为了OP的缘故,你可以把这个在问题标记被标记的VB语法中? – Codexer

+0

好吧,对不起,我会更新我的答案,谢谢 – Rosenumber14

+0

因此,这将使控制台等待,但在同一时间让其他代码保持运行? – Obfuscated