2017-01-11 64 views
0

我想在foreach循環時更新標籤。在foreach循環中更改標籤文本

問題是:程序一直等到循環完成,然後更新標籤。

是否有可能在foreach循環期間更新標籤?

代碼:

Dim count as Integer = 0 
For Each sFile as String in Files 
    'ftp-code here, works well 
    count = count+1 
    progressbar1.value = count 
    label1.text = "File " & count & " of 10 uploaded." 
next 

由於事先沒有更新

+0

你有沒有試過這段代碼?結果是什麼? – ADyson

+0

答案是肯定的。儘管你應該先嚐試一下,因爲你會回答你自己的問題。 –

+0

它確實,但我猜你想看到它反映,因爲它更新而不是UI凍結?這是問題嗎? – Bugs

回答

2

標籤,因爲在執行您的foreach迴路UI線程被阻塞。
您可以使用async-await方法

Private Async Sub Button_Click(sender As Object, e As EventArgs) 
    Dim count as Integer = 0 
    For Each sFile as String in Files 
     'ftp-code here, works well 
     count = count+1 

     progressbar1.value = count 
     label1.text = "File " & count & " of 10 uploaded." 

     Await Task.Delay(100) 
    Next 
End Sub 

因爲你將與FTP連接,這是使用async-await完美的候選人的工作。

Await行將釋放UI線程,該線程將用新值更新標籤,並在100毫秒後從該行繼續。

如果您將使用FTP連接異步代碼,那麼你不需要Task.Delay

+0

我的程序不識別'任務'。還有什麼我應該知道的事情嗎?也許我只是誤解了你的意思。 – neverlucky

+1

您需要參考'System.Threading.Tasks' – Fabio

0

您已接受的答案,但只是作爲一種替代一個BackgroundWorker也可以使用這樣的事情。在我的情況下,獲取原始文件的FTP發生得非常快,因此DoWork事件中的這個片段用於將這些文件下載到打印機。

Dim cnt As Integer = docs.Count 
Dim i As Integer = 1 
For Each d As String In docs 
    bgwTest.ReportProgress(BGW_State.S2_UpdStat, "Downloading file " & i.ToString & " of " & cnt.ToString) 

    Dim fs As New IO.FileStream(My.Application.Info.DirectoryPath & "\labels\" & d, IO.FileMode.Open) 
    Dim br As New IO.BinaryReader(fs) 
    Dim bytes() As Byte = br.ReadBytes(CInt(br.BaseStream.Length)) 

    br.Close() 
    fs.Close() 
    For x = 0 To numPorts - 1 
     If Port(x).IsOpen = True Then 
      Port(x).Write(bytes, 0, bytes.Length) 
     End If 
    Next 
    If bytes.Length > 2400 Then 
     'these sleeps are because it is only 1-way comm to printer so I have no idea when printer is ready for next file 
     System.Threading.Thread.Sleep(20000) 
    Else 
     System.Threading.Thread.Sleep(5000) 
    End If 

    i = i + 1 
Next 

在ReportProgress事件......(當然,你需要設置WorkerReportsProgress屬性爲True)

Private Sub bgwTest_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgwTest.ProgressChanged 

    Select Case e.ProgressPercentage 
     'BGW_State is just a simple enum for the state, 
     'which determines which UI controls I need to use. 
     'Clearly I copy/pasted from a program that had 15 "states" :) 
     Case BGW_State.S2_UpdStat 
      Dim s As String = CType(e.UserState, String) 
      lblStatus.Text = s 
      lblStatus.Refresh() 

     Case BGW_State.S15_ShowMessage 
      Dim s As String = CType(e.UserState, String) 
      MessageBox.Show(s) 

    End Select 

End Sub 
-1

難道不夠用Application.DoEvents()?這清除了構建,你應該能夠看到正在更新文本字段很快。

+0

[DoEvents Evil?](https://blog.codinghorror.com/is-doevents-evil/),[使用Application.DoEvents()](http ://stackoverflow.com/a/5183623/1115360)。 –