How to use timer for for next loop in visual basic 2008 - vb.net

I have a case where i need to generate millions of unique codes. For this I have created a generate function where the random number is generated. I call this function from a for loop and add the generated number on a list box. my code is as follow
for i=1 to val(txtnumber.txt)
mynum=generate()
next
I have created a lable on form where i wanted to display the no of secs elapsed while processing the loop. I used timer control as
timer1.start()
for i=1 to val(txtnumber.text)
mynum=generate()
listbox1.items.add(mynum)
next
timer1.stop
and on timer1_tick function
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
but when i click generate button, all numbers are generated, but timer doesnot shows time elapsed.
I may have missed something, so please help me out

This is probably best handled in a BackgroundWorker. Place one on the form and set its WorkerReportsProgress=True. Also, placing a million numbers in a ListBox probably isn't a good idea, so I omitted that.
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
Your label should be updating correctly when the worker reports the ProgressChanged event.

What you're encountering is a threading issue. The work you are doing to generate the numbers is being executing by the UI thread, so it never gets a chance to update the screen. Take a look here: How to prevent UI from freezing during lengthy process?
This one might also have good information for you: Updating UI from another thread

Try this:
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
Or you can research actual Threading.

Related

StopWatch and Timer Accuracy

I'm using the following code to control a label to output a stopwatch. The buttons work, and the label is outputting the information mostly correctly, however it only update every so often and i would like for the label to update the information every millisecond.
Private SW As New Stopwatch
Dim timercount As Integer = 1 'The number of seconds
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
SW.Start()
Timer1.Start()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Timer1.Enabled = False 'Stop the timer
timercount = 0 'Reset to 0 seconds
Label10.Text = "00:00:00.000"
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim ts As TimeSpan = SW.Elapsed
Label10.Text = ts.ToString("hh\:mm\:ss\.fff")
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Timer1.enabled = False
End Sub
Any help is much appreciated.
You can set the timer to a reasonable value, say 20 times a second, to rapidly display it changing.
You can create the timer and stopwatch in code, which I think is easier than adding a control to the form—you can see right there in the code what is being programmed. I used sensible names for the buttons so that you can tell what is meant to do what.
If you keep the sub to display the data separate from the code that processes the data, it is easy to change the display in just one place, in case someone decided they wanted it written as words, for example, or maybe the hours in a separate box, or something.
Public Class Form1
Dim sw As New Stopwatch
Dim tim As Timer
Private Sub ShowElapsedTime()
lblTime.Text = sw.Elapsed.ToString("hh\:mm\:ss\.fff")
End Sub
Private Sub bnStart_Click(sender As Object, e As EventArgs) Handles bnStart.Click
sw.Restart()
tim.Enabled = True
End Sub
Private Sub bnStop_Click(sender As Object, e As EventArgs) Handles bnStop.Click
sw.Stop()
tim.Enabled = False
ShowElapsedTime()
End Sub
Private Sub bnReset_Click(sender As Object, e As EventArgs) Handles bnReset.Click
tim.Enabled = False
sw.Reset()
ShowElapsedTime()
End Sub
Private Sub tim_Tick(sender As Object, e As EventArgs)
ShowElapsedTime()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
tim = New Timer With {.Interval = 50}
AddHandler tim.Tick, AddressOf tim_Tick
ShowElapsedTime()
End Sub
End Class

VB.net Update Label Each Second

In my application i have a label that displays the current time in HH:mm:ss
How can i get the label to update its content each second so that the time actually is correct?
Add a Timer to your project. Set the Interval property to 1000. Then...
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = 'Your code
End Sub

visual basic game player wont move

For a school project I am making a simple game were zombie's walk straight down and try to attack the players base (it is kinda like space invaders and planets versus zombies). however my player has stopped moving when I press D or A, when I try to play the game. I will post my code. can somebody help make my player move side to side?.
Public Class Form2
Dim Player_Health As Integer = 10
Dim Player_Max_Health As Integer = 100
Dim Player_X_Speed_Moving As Integer = 0
Dim Player_Potential_X_Speed As Integer = 10
Private Sub Form2_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.A Then
Player_X_Speed_Moving = -Player_Potential_X_Speed
End If
If e.KeyCode = Keys.D Then
Player_X_Speed_Moving = Player_Potential_X_Speed
End If
End Sub
Private Sub Form2_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
If e.KeyCode = Keys.A Then
Player_X_Speed_Moving = 0
End If
If e.KeyCode = Keys.D Then
Player_X_Speed_Moving = 0
End If
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim bmp As Bitmap = Bitmap.FromFile("C:\Users\Kevin Welch\Documents\Visual Studio 2010\Projects\Zom-b\Zom-b\My Project\Res\Spr\Player1.bmp")
bmp.MakeTransparent(Color.White) ' magenta in bitmap will be transparent
PictureBox1.Image = bmp
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Call MovePlayer()
End Sub
Private Sub MovePlayer()
PictureBox1.Left += Player_X_Speed_Moving
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Form1.Show()
Me.Hide()
End Sub
End Class
My guess would be that the form's message queue is getting backed up with key down events and your Tick event is having trouble keeping up. Most window UI systems use a single thread that responds to messages that are pumped to them such as key down/up, mouse movements, and clicks. If the UI thread is busy, your Tick event will have to wait since it runs on the same thread. Many games have a game loop that processes window events along with processing game logic and graphics rendering. I would recommend look into using the XNA Framework since it handles most of that stuff for you.

vb net backgroundworker + progress bar

i want to create automatic progress bar that will popped up when i ran my program..
my program has 6 function/sub which run query that took quite long time to completed, it's approximately around 1-2 minutes regarding input
i'm using backgroundworker to handle the threads and combine it with progressbar
here's my code
RunWorkerAsync
Private Sub ButtonX1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonX1.Click
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.RunWorkerAsync()
End Sub
Do_work
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For i As Integer = 0 To 100000000
create_tree()
localtree()
localfrek()
create_combination()
showresult()
If i Mod 10000000 Then
BackgroundWorker1.ReportProgress(i / 100)
End If
Next
End Sub
ProgressChanged
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ProgressBar1.Visible = True
ProgressBar1.Value = e.ProgressPercentage
End Sub
RunWorkerCompleted
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Task completed!")
End Sub
the problem is
the the progress bar didn't popped up
the function stop before completion
for the second problem i think it because the for loop that i use in Do_work event
i don't know the elapsed time of each function that i have, so i use random integer number in for loop
can you please help me to correct my program? thank you very much.. :)
Firstly, you should be setting the Visible property of the ProgressBar before you call RunWorkerAsync.
Secondly, you should be comparing i Mod 10000000 to something.
Thirdly, if i goes up to 10000000 then i / 100 is going to go beyond 100.

VB.Net - Updating progress bar from background worker

I am trying to build a log parser in VB.Net that will take IIS logs and insert them into a database. Having never really made a full out desktop application, I'm hitting a number of stumbling blocks, so please forgive me if my questions a very uninformed; I'm learning to walk while running.
The code that I'm working with looks like this:
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim logfile = "C:\ex111124.log"
Dim FileLength As Long = New System.IO.FileInfo(logfile).Length
logFileLabel.Text = logfile
Dim objReader As New System.IO.StreamReader(logfile)
Do While objReader.Peek() <> -1
OngoingLog.AppendText(objReader.ReadLine)
'BackgroundWorker1.ReportProgress(e.percentProgress)
Loop()
objReader.Close()
objReader = Nothing
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
'Me.crunchingProgress.Value = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Close()
End Sub
So the function works, when this window is opened it starts to read the log file and updates a textbox with all of the rows currently read, but I also want it to update a progress bar in my main thread called crunchingProgress.
Any help would be greatly appreciated.
This should do the trick:
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Invoke(Sub()
Me.crunchingProgress.Value = e.ProgressPercentage
End Sub)
End Sub
You don't set the BackgroundWorker to report progress (WorkerReportsProgress)
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.RunWorkerAsync()
Now your BackgroundWorker1_ProgressChanged will be called in the context of the UI Thread and you can set the progressbar value
Of course, when you call ReportProgress to raise the ProgressChanged event, you need to pass the percentage of work done so far.
Using objReader As New System.IO.StreamReader(logfile)
Do While objReader.Peek() <> -1
Dim line = objReader.ReadLine()
OngoingLog.AppendText(line)
Dim pct = Convert.ToInt32((100 * line.Length) / FileLength )
BackgroundWorker1.ReportProgress(pct)
Loop
End Using