我有一个案例需要生成数百万个唯一代码。为此我创建了一个生成函数,其中生成随机数。我从for循环中调用此函数,并在列表框中添加生成的数字。我的代码如下
for i=1 to val(txtnumber.txt)
mynum=generate()
next
我在表单上创建了一个标签,我希望在处理循环时显示已经过的秒数。我使用计时器控制作为
timer1.start()
for i=1 to val(txtnumber.text)
mynum=generate()
listbox1.items.add(mynum)
next
timer1.stop
和timer1_tick函数
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Label1.Text = Val(Label1.Text) + 1
End Sub
但是当我点击生成按钮时,会生成所有数字,但计时器不显示已过去的时间。
我可能错过了什么,所以请帮帮我
答案 0 :(得分:3)
这可能最适合在BackgroundWorker中处理。在表单上放置一个并设置其WorkerReportsProgress=True
。另外,在ListBox中放置一百万个数字可能不是一个好主意,所以我省略了它。
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Button1.Enabled = False
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim started As DateTime = Now
For i As Integer = 1 To val(txtnumber.txt)
mynum=generate()
BackgroundWorker1.ReportProgress(i, Nothing)
Next
Dim ended As TimeSpan = Now.Subtract(started)
BackgroundWorker1.ReportProgress(0, ended.TotalSeconds.ToString)
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
If e.UserState IsNot Nothing Then
Label1.Text = e.UserState.ToString()
Else
Label1.Text = e.ProgressPercentage.ToString
End If
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Button1.Enabled = True
End Sub
当工作人员报告ProgressChanged
事件时,您的标签应该正确更新。
答案 1 :(得分:1)
您遇到的是线程问题。您正在执行的生成数字的工作正在由UI线程执行,因此它永远不会有机会更新屏幕。看看这里:How to prevent UI from freezing during lengthy process?
这个可能也有适合您的信息:Updating UI from another thread
答案 2 :(得分:0)
试试这个:
Private _Counter As Integer = 0
Private _StartTime As Date = Now
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
_StartTime = Now
_Counter = CInt(Val(txtnumber.Text))
ListBox1.Items.Clear()
Label1.Text = "0"
Timer1.Interval = 50
Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
ListBox1.Items.Add(generate())
Label1.Text = New Date((Now - _StartTime).Ticks).ToString("HH:mm:ss.ff")
_Counter -= 1
If (_Counter <= 0) Then
Timer1.Stop()
End If
End Sub
或者您可以研究实际的Threading。