2017-09-01 111 views
0

試圖編寫一個需要以x分鐘或x小時運行任務的小應用程序。 我面對的是計算x時間的方式,以便在指定的分鐘或小時運行任務。如何以x時間(分鐘和小時)運行任務

我的應用程序很簡單:一個分鐘(1到59)的列表框和一個文本框,用於輸入要在指定時間顯示的消息。 所以當用戶選擇50分鐘,並輸入「你好」,程序50分鐘後,它必須顯示一個消息框與「你好」的消息,並應該有多線程,以避免Ui封鎖時運行一個任務,另一個也應該被運行。

我試圖用For ... Loop來計算每秒,但我沒有得到預期的結果。

Dim s as string 
 

 
For Each s in myVariable 
 
    console.writeLine("Message") 
 
Next

+1

[定時器](https://msdn.microsoft.com/en-us/library/system.timers.timer(v = vs.110).aspx)會爲您節省一些時間! –

+0

我應該放多少個計時器?因爲任務的數量未知。我該如何處理? – user8189

+0

如果你至少可以閱讀文檔,你會得到一個大概的想法。此外谷歌關於計時器得到相同的例子 –

回答

0

可以使用Thread.Sleep(milliseconds)達到你想要什麼

Dim s as string = "Hi" 
 

 
Thread.Sleep(1000) 
 
console.writeLine("Message")
它必須在一個新的線程來完成

參考在https://www.dotnetperls.com/sleep-vbnet

或者你可以使用一個Timer

Imports Microsoft.VisualBasic 
Imports System.Timers 

Public Class TimerTest 
    Shared _timer As Timer 
    Shared _list As List(Of String) = New List(Of String) 

    ''' <summary> 
    ''' Start the timer. 
    ''' </summary> 
    Shared Sub Start() 
     _timer = New Timer(3000) 
     AddHandler _timer.Elapsed, New ElapsedEventHandler(AddressOf Handler) 
     _timer.Enabled = True 
    End Sub 

    ''' <summary> 
    ''' Get timer output. 
    ''' </summary> 
    Shared Function GetOutput() As String 
     Return String.Join("<br>", _list) 
    End Function 

    ''' <summary> 
    ''' Timer event handler. 
    ''' </summary> 
    Shared Sub Handler(ByVal sender As Object, ByVal e As ElapsedEventArgs) 
     _list.Add(DateTime.Now.ToString()) 
    End Sub 
End Class 

來自實例https://www.dotnetperls.com/timer-vbnet

創建每按一下按鈕一個定時器,你就大功告成了:)

+0

謝謝大家,抱歉,因爲我離開了延遲。 – user8189

0

如果程序後,應顯示的消息選定的分鐘數量,那麼你可以使用異步方法。

' When combobox value changed 
Private Async Sub ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) 
    Dim comboBox = DirectCase(sender, ComboBox) 
    Dim minutesAmount = DirectCast(comboBox.SelectedItem, Integer) 

    await Task.Delay(minutesAmount * 60000) 

    MessageBox.Show("Hello") 
End Sub 

Task.Delay會等到毫秒一定量的經過,並繼續執行下一行。
await Task.Delay不會阻止UI線程