Timer tick when the for loop is completed - vb.net

How can I tick the timer when the for loop is completed? I don't want to run the timer every X minute, I want to run the timer when the button is clicked and then just tick the timer again when the for loop is completed..
For Each row As DataRow In MTProcessTable.Rows
Try
If checkKeyHelp(process.datain) Then
msg = msgTable.Rows(1)(1).ToString()
MsgBox(msg)
writeMsg("1 MO help at ")
ElseIf checkKeyInfo(process.datain) Then
msg = msgTable.Rows(4)(1).ToString()
MsgBox(msg)
writeMsg("1 MO INFO at ")
Else
MOTable = selectMO(process.mo, process.mt)
moRowNb = MOTable.Rows.Count()
MO = New MO_class
If moRowNb <> 0 Then
MOrow = MOTable.Rows(0)
MO.newuser = MOrow("newuser")
MO.sim_id = MOrow("sim_id")
End If
Catch ex As Exception
logFile("executeTimer ----" & ex.Message)
updateProcessed(process.id, ex.Message)
Finally
updateProcessed(process.id, msg)
End Try
Next row
Private Sub start_btn_Click(sender As System.Object, e As System.EventArgs) Handles start_btn.Click
Timer1.Enabled = True
tm.StartTimer()
End Sub

Based on your comment, it sounds like you want to write a program that will select data and process it. Once that is complete, you want to start the process over by selecting new data and processing that, etc. etc.
If you want to use a timer, I would set it up as follows. It will use a few shared items to start or stop the timer which runs the sub. One problem is that while it is running, the program will be unresponsive. The only time you can 'stop' the program is during the time in between runs. I have the time between threads set to 10 seconds (10000 ms), but you can use any value.
Imports System.Windows.Forms.Timer
Public Class Form1
Private Sub RunProcess()
'Add code to populate datatable
For Each row As DataRow In MTProcessTable.Rows
Try
If checkKeyHelp(Process.datain) Then
msg = msgTable.Rows(1)(1).ToString()
MsgBox(msg)
writeMsg("1 MO help at ")
ElseIf checkKeyInfo(Process.datain) Then
msg = msgTable.Rows(4)(1).ToString()
MsgBox(msg)
writeMsg("1 MO INFO at ")
Else
MOTable = selectMO(Process.mo, Process.mt)
moRowNb = MOTable.Rows.Count()
MO = New MO_class
If moRowNb <> 0 Then
MOrow = MOTable.Rows(0)
MO.newuser = MOrow("newuser")
MO.sim_id = MOrow("sim_id")
End If
End If
Catch ex As Exception
logFile("executeTimer ----" & ex.Message)
updateProcessed(Process.Id, ex.Message)
Finally
updateProcessed(Process.Id, msg)
End Try
Next row
Timer1.Enabled = True
End Sub
Private Timer1 As Timer 'Create timer
Sub Timer1_Tick() 'Handle timer tick
Timer1.Enabled = False
RunProcess()
End Sub
Private blRunning As Boolean
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1 = New Timer 'Create instance of timer
Timer1.Interval = 10000 'Time in MS before starting next process
AddHandler Timer1.Tick, AddressOf Timer1_Tick 'Add tick handler to timer
Timer1.Enabled = blRunning 'Enable/disable timer
End Sub
Private Sub start_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles start_btn.Click
If blRunning = True Then
blRunning = False
start_btn.Text = "Start"
Else
blRunning = True
start_btn.Text = "Stop"
End If
Timer1.Enabled = blRunning
End Sub
End Class

Related

backgroundworder error - index was outside the bounds of the array vb.net

I was trying to ceate a program using vb.net. A program that use Backgroundworkder while importing an excel file "Stock.xlsx" to datagridview. But when I click start button, it comes to an error "index was outside the bounds of the array". Please someone help me guys.
Please see below program and snapshot error:
Public Class Form1
Dim strRow As String() 'String array to read all fields in a row
Dim dblAmount As Double 'Variable for total amount
Dim blnReported As Boolean = True 'Flag to check progress report completed or not
'Create TextFieldParser class to parse the stock.csv file in the current location
Dim txtFile As FileIO.TextFieldParser
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Allow background operation to be cancelled
bgWorker.WorkerSupportsCancellation = True
'Allow background operation to report progress
bgWorker.WorkerReportsProgress = True
'Disable Stop Button. It is enabled only after start
'button is pressed
btnStop.Enabled = False
'set status message
lblStatus.Text = "Press Start to import data from csv."
'Add columns to the grid
dgvCSVData.Columns.Add("colNo", "No")
dgvCSVData.Columns("colNo").Width = 30
dgvCSVData.Columns.Add("colDate", "Date")
dgvCSVData.Columns("colDate").Width = 60
dgvCSVData.Columns.Add("colItem", "Item")
dgvCSVData.Columns("colItem").Width = 120
dgvCSVData.Columns.Add("colQty", "Quantity")
dgvCSVData.Columns("colQty").Width = 50
dgvCSVData.Columns.Add("colUnit", "Unit")
dgvCSVData.Columns("colUnit").Width = 30
dgvCSVData.Columns.Add("colAmt", "Amt")
dgvCSVData.Columns("colAmt").Width = 60
End Sub
Private Sub btnStart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnStart.Click
'Disable Start button and Enable Stop
btnStart.Enabled = False
btnStop.Enabled = True
'set status message
lblStatus.Text = "Importing data from CSV file."
'Start time-consuming operation in background
Call bgWorker.RunWorkerAsync()
End Sub
Private Sub btnStop_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnStop.Click
'Enable Start button and disable Stop
btnStart.Enabled = True
btnStop.Enabled = False
'Stop background operation
bgWorker.CancelAsync()
'set status message
lblStatus.Text = "Import cancelled. Press Start again."
End Sub
Private Sub bgWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker.DoWork
Dim intCount As Int16 = 0
txtFile = New FileIO.TextFieldParser("stock.xlsx")
'Specify structure of the file
txtFile.TextFieldType = FileIO.FieldType.Delimited
txtFile.SetDelimiters(",")
'Skip header row
txtFile.ReadFields()
'Start reading data from file
While Not txtFile.EndOfData
If bgWorker.CancellationPending Then
e.Cancel = True
Exit Sub
Else
'Wait for Progress Report to finish
While Not blnReported
Application.DoEvents()
End While
'Read all field in a row into a string array
strRow = txtFile.ReadFields()
'Do some calculations and assign value to data grid
dblAmount = CDbl(strRow(3)) * CDbl(strRow(4))
'Add some sleep to simulate a long running operation
System.Threading.Thread.Sleep(500)
'Progress report pending
blnReported = False
'increment counter
intCount += 1
'Report the progress
bgWorker.ReportProgress(10, intCount)
End If
End While
End Sub
Private Sub bgWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgWorker.ProgressChanged
'Copy values to data grid
dgvCSVData.Rows.Add(strRow)
dgvCSVData.Rows(dgvCSVData.CurrentRow.Index - 1).Cells("colAmt").Value = dblAmount
pgbCopyProgress.Value = e.UserState
'Progress report finished
blnReported = True
End Sub
Private Sub bgWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgWorker.RunWorkerCompleted
If e.Cancelled Or Not IsNothing(e.Error) Then
'Clear the data grid
dgvCSVData.Rows.Clear()
Else
'Progress completed
pgbCopyProgress.Value = 100
'Release txtfile
txtFile.Dispose()
btnStop.Enabled = False
btnStart.Enabled = True
End If
End Sub
End Class
When doing strRow(3) or strRow(4), you are trying to access the 4th and 5th elements of the array. It seems the array doesn't have that many elements.
Also, it's a good habit to check the array's length before accessing elements.

Visual Basic - start stopwatch for measuring overtime after a given amount of minutes

I'm starting my first steps into Visual Basic and trying to create sort of a stopwatch.
My design is the following:
The idea behind is to create a tool to support a debate. Persons gets a certain time (7 minutes) for presenting their topic and after that time there is room for interactive conversation (Q&A) set to 13 minutes. The idea is that after 7 minutes a buzzer sounds to stop the presenting time and go over to the interactive part. And after 20 minutes a 2nd stopwatch starts with a buzzer and a red flashing background to indicate that session needs to be terminated.
This is what I already got and I'm pretty shure it can be coded otherwise and maybe easier.
I already got it to the first working stopwatch but I don't get the rest working:
Public Class Form1
Private Hundredths As Integer = 0
Private Seconds As Integer = 0
Private Minutes As Integer = 0
Private Hours As Integer = 0
Private OvertimeHundredths As Integer = 0
Private OvertimeSeconds As Integer = 0
Private OvertimeMinutes As Integer = 0
Private OvertimeHours As Integer = 0
Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click
If Timer1.Enabled Then
Timer1.Stop()
StartBtn.Text = "START"
Return
End If
If Not Timer1.Enabled Then
Timer1.Start()
StartBtn.Text = "STOP"
Return
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Hundredths += 1
HundredthsTxB.Text = Hundredths.ToString
SecondsTxB.Text = Seconds.ToString
MinutesTxB.Text = Minutes.ToString
HoursTxB.Text = Hours.ToString
If Hundredths = 10 Then
Seconds += 1
Hundredths = 0
End If
If Seconds = 60 Then
Minutes += 1
Seconds = 0
End If
If Minutes = 60 Then
Hours += 1
Minutes = 0
End If
If Hours = 24 Then
Timer1.Stop()
End If
End Sub
Private Sub ResetBtn_Click(sender As Object, e As EventArgs) Handles ResetBtn.Click
Hundredths = 0
Seconds = 0
Minutes = 0
Hours = 0
HundredthsTxB.Text = Hundredths.ToString
SecondsTxB.Text = Seconds.ToString
MinutesTxB.Text = Minutes.ToString
HoursTxB.Text = Hours.ToString
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
OvertimeHundredths += 1
OvertimeHundredthsTxB.Text = OvertimeHundredths.ToString
OvertimeSecondsTxB.Text = OvertimeSeconds.ToString
OvertimeMinutesTxB.Text = OvertimeMinutes.ToString
OvertimeHoursTxB.Text = OvertimeHours.ToString
If OvertimeHundredths = 10 Then
OvertimeSeconds += 1
OvertimeHundredths = 0
End If
If OvertimeSeconds = 60 Then
OvertimeMinutes += 1
OvertimeSeconds = 0
End If
If OvertimeMinutes = 60 Then
OvertimeHours += 1
OvertimeMinutes = 0
End If
If OvertimeHours = 24 Then
Timer2.Stop()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Timer1.Interval = 2 Then
Timer2.Start()
End If
End Sub
End Class
So any help is welcome. Also I'm keen on learning on how other guru's are thinking and coding.
Instead of using timers, I would use a Stopwatch. This way there is less messing around adding numbers etc. The code below accomplishes what you want apart from sounding a buzzer as I'm presuming you want to implement it your own. It looks worse than it is, but seems to work ok. See code comments for a little explanation
Public Class Form1
Private PresentationTimer As New Stopwatch
Private InteractiveTimer As New Stopwatch
Private PresentationMinutes As Integer
Private InteractiveMinutes As Integer
'When this timer is enabled, it keeps track of the two stopwatches and checks
'that they're within the alloted time.
'
'When the presentation timer has expired, that one is stopped and the interactive
'timer is started
'
'When the interactive timer has expired, the timer for background flashing starts.
'To stop the flashing, click the reset button on the form
Private Sub UiUpdateTimer_Tick(sender As Object, e As EventArgs) Handles uiUpdateTimer.Tick
UpdateUI()
If PresentationTimer.IsRunning And IsTimeExpired(PresentationTimer, PresentationMinutes) Then
PresentationTimer.Stop()
InteractiveTimer.Start()
'add code here for buzzer to show end of presentation time
End If
If InteractiveTimer.IsRunning And IsTimeExpired(InteractiveTimer, InteractiveMinutes) Then
InteractiveTimer.Stop()
BackgroundFlashTimer.Enabled = True
'add code here for buzzer to show end of interactive time
StartBtn.Text = "START"
End If
End Sub
'checks if the timer passed as a parameter is expired by comparing
'the number of elapsed minutes with the number of minutes passed in
'the second parameter
Private Function IsTimeExpired(tmr As Stopwatch, mins As Integer) As Boolean
If tmr.Elapsed.Minutes >= mins Then
Return True
Else
Return False
End If
End Function
'simply updates all the textboxes with the stopwatch values.
Private Sub UpdateUI()
HundredthsTxB.Text = Int(PresentationTimer.Elapsed.Milliseconds / 10).ToString
SecondsTxB.Text = PresentationTimer.Elapsed.Seconds.ToString
MinutesTxB.Text = PresentationTimer.Elapsed.Minutes.ToString
HoursTxB.Text = PresentationTimer.Elapsed.Hours.ToString
OvertimeHundredthsTxB.Text = Int(InteractiveTimer.Elapsed.Milliseconds / 10).ToString
OvertimeSecondsTxB.Text = InteractiveTimer.Elapsed.Seconds.ToString
OvertimeMinutesTxB.Text = InteractiveTimer.Elapsed.Minutes.ToString
overtimeHoursTxB.Text = InteractiveTimer.Elapsed.Hours.ToString
End Sub
Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click
'if either timer is running, stop them both and exit this sub
If PresentationTimer.IsRunning Or InteractiveTimer.IsRunning Then
PresentationTimer.Stop()
InteractiveTimer.Stop()
StartBtn.Text = "START"
uiUpdateTimer.Enabled = False
Exit Sub
End If
'if the presentation timer hasn't run yet, check if the minutes values are
'valid and start it
If PresentationTimer.ElapsedMilliseconds = 0 Then
PresentationMinutes = CInt(Val(PresentationMinutesTxB.Text))
InteractiveMinutes = CInt(Val(InteractiveMinutesTxB.Text))
'if the minutes values are't valid show messagebox and exit this sub
If PresentationMinutes = 0 Or InteractiveMinutes = 0 Then
MessageBox.Show("Please enter valid Presentation and Interactive times.")
Exit Sub
End If
'if minutes values are ok start the presentation timer
uiUpdateTimer.Enabled = True
PresentationTimer.Start()
StartBtn.Text = "STOP"
Exit Sub
End If
'if the presentation timer has been running, but is currently stopped,
'continue the timer and exit this sub
If Not PresentationTimer.IsRunning And PresentationTimer.ElapsedMilliseconds > 0 Then
uiUpdateTimer.Enabled = True
PresentationTimer.Start()
StartBtn.Text = "STOP"
Exit Sub
End If
'if the interactive timer has been running,but is currently stopped,
'continue the timer and exit this sub
If Not InteractiveTimer.IsRunning And InteractiveTimer.ElapsedMilliseconds > 0 Then
uiUpdateTimer.Enabled = True
InteractiveTimer.Start()
StartBtn.Text = "STOP"
Exit Sub
End If
End Sub
Private Sub ResetBtn_Click(sender As Object, e As EventArgs) Handles ResetBtn.Click
PresentationTimer.Reset()
InteractiveTimer.Reset()
uiUpdateTimer.Enabled = False
StartBtn.Enabled = True
StartBtn.Text = "START"
UpdateUI()
BackgroundFlashTimer.Enabled = False
Me.BackColor = defaultBackColor
End Sub
Private Sub BackgroundFlashTimer_Tick(sender As Object, e As EventArgs) Handles BackgroundFlashTimer.Tick
StartBtn.Enabled = False
If Me.BackColor = DefaultBackColor Then
Me.BackColor = Color.Red
Else
Me.BackColor = DefaultBackColor
End If
Me.Update()
End Sub
End Class
This was my final solution based on David Wilson's contribution:
Public Class Form1
Private PresentationTimer As New Stopwatch
Private InteractiveTimer As New Stopwatch
Private ExtraTimeTimer As New Stopwatch
Private PresentationMinutes As Integer
Private InteractiveMinutes As Integer
'When this timer is enabled, it keeps track of the two stopwatches and checks
'that they're within the alloted time.
'
'When the presentation timer has expired, that one is stopped and the interactive
'timer is started
'
'When the interactive timer has expired, the timer for background flashing starts.
'To stop the flashing, click the reset button on the form
Private Sub uiUpdateTimer_Tick(sender As Object, e As EventArgs) Handles uiUpdateTimer.Tick
UpdateUI()
If PresentationTimer.IsRunning And IsTimeExpired(PresentationTimer, PresentationMinutes) Then
PresentationTimer.Stop()
InteractiveTimer.Start()
Me.BackColor = Color.Yellow
'add code here for buzzer to show end of presentation time
End If
If InteractiveTimer.IsRunning And IsTimeExpired(InteractiveTimer, InteractiveMinutes) Then
InteractiveTimer.Stop()
BackgroundFlashTimer.Enabled = True
ExtraTimeTimer.Start()
'add code here for buzzer to show end of interactive time
StartBtn.Text = "START"
End If
End Sub
'checks if the timer passed as a parameter is expired by comparing
'the number of elapsed minutes with the number of minutes passed in
'the second parameter
Private Function IsTimeExpired(tmr As Stopwatch, mins As Integer) As Boolean
If tmr.Elapsed.Minutes >= mins Then
Return True
Else
Return False
End If
End Function
'simply updates all the textboxes with the stopwatch values.
Private Sub UpdateUI()
HundredthsTxB.Text = Int(PresentationTimer.Elapsed.Milliseconds / 10).ToString
SecondsTxB.Text = PresentationTimer.Elapsed.Seconds.ToString
MinutesTxB.Text = PresentationTimer.Elapsed.Minutes.ToString
HoursTxB.Text = PresentationTimer.Elapsed.Hours.ToString
OvertimeHundredthsTxB.Text = Int(InteractiveTimer.Elapsed.Milliseconds / 10).ToString
OvertimeSecondsTxB.Text = InteractiveTimer.Elapsed.Seconds.ToString
OvertimeMinutesTxB.Text = InteractiveTimer.Elapsed.Minutes.ToString
OvertimeHoursTxB.Text = InteractiveTimer.Elapsed.Hours.ToString
ExtraTimeHundredthsTxB.Text = Int(ExtraTimeTimer.Elapsed.Milliseconds / 10).ToString
ExtraTimeSecondsTxB.Text = ExtraTimeTimer.Elapsed.Seconds.ToString
ExtraTimeMinutesTxB.Text = ExtraTimeTimer.Elapsed.Minutes.ToString
ExtraTimeHoursTxB.Text = ExtraTimeTimer.Elapsed.Hours.ToString
End Sub
Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click
'if either timer is running, stop them both and exit this sub
If PresentationTimer.IsRunning Or InteractiveTimer.IsRunning Then
PresentationTimer.Stop()
InteractiveTimer.Stop()
ExtraTimeTimer.Stop()
StartBtn.Text = "START"
uiUpdateTimer.Enabled = False
Exit Sub
End If
'if the presentation timer hasn't run yet, check if the minutes values are
'valid and start it
If PresentationTimer.ElapsedMilliseconds = 0 Then
PresentationMinutes = CInt(Val(PresTimeTxB.Text))
InteractiveMinutes = CInt(Val(InterTimeTxB.Text))
'if the minutes values are't valid show messagebox and exit this sub
If PresentationMinutes = 0 Or InteractiveMinutes = 0 Then
MessageBox.Show("Please enter valid Presentation and Interactive times.")
Exit Sub
End If
'if minutes values are ok start the presentation timer
uiUpdateTimer.Enabled = True
PresentationTimer.Start()
StartBtn.Text = "STOP"
Exit Sub
End If
'if the presentation timer has been running, but is currently stopped,
'continue the timer and exit this sub
If Not PresentationTimer.IsRunning And PresentationTimer.ElapsedMilliseconds > 0 Then
uiUpdateTimer.Enabled = True
PresentationTimer.Start()
StartBtn.Text = "STOP"
Exit Sub
End If
'if the interactive timer has been running,but is currently stopped,
'continue the timer and exit this sub
If Not InteractiveTimer.IsRunning And InteractiveTimer.ElapsedMilliseconds > 0 Then
uiUpdateTimer.Enabled = True
InteractiveTimer.Start()
StartBtn.Text = "STOP"
Exit Sub
End If
End Sub
Private Sub ResetBtn_Click(sender As Object, e As EventArgs) Handles ResetBtn.Click
PresentationTimer.Reset()
InteractiveTimer.Reset()
ExtraTimeTimer.Reset()
uiUpdateTimer.Enabled = False
StartBtn.Enabled = True
StartBtn.Text = "START"
UpdateUI()
BackgroundFlashTimer.Enabled = False
Me.BackColor = DefaultBackColor
End Sub
Private Sub BackgroundFlashTimer_Tick(sender As Object, e As EventArgs) Handles BackgroundFlashTimer.Tick
StartBtn.Enabled = False
If Me.BackColor = DefaultBackColor Then
Me.BackColor = Color.Red
Else
Me.BackColor = DefaultBackColor
End If
Me.Update()
End Sub

BackgroundWorker's ProgressChanged not updating UI until end of work loop

I am coding a WPF application that will grab email's off of an IMAP account, and then export them into a user-selected folder.
I use a BackgroundWorker to download the emails. However, my UI isn't being updated until the loop is over.
Any tips would be appreciated.
Class MainWindow
Public MailRepo As MailRepository
Private bw_Connect As New BackgroundWorker
Private bw_Save As New BackgroundWorker
Public Sub New()
InitializeComponent()
bw_Connect.WorkerReportsProgress = True
bw_Connect.WorkerSupportsCancellation = True
AddHandler bw_Connect.DoWork, AddressOf bw_Connect_DoWork
bw_Save.WorkerReportsProgress = True
bw_Save.WorkerSupportsCancellation = True
AddHandler bw_Save.DoWork, AddressOf bw_Save_DoWork
AddHandler bw_Save.ProgressChanged, AddressOf bw_Save_ProgressChanged
End Sub
Private Sub bw_Save_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
If bw_Connect.CancellationPending = True Then
e.Cancel = True
Else
SaveEmails()
End If
End Sub
Private Sub SaveEmails()
Dim allMails As IEnumerable(Of Message)
'Get All Emails in Mailbox
Try
Dim mailBox As String
Dispatcher.Invoke(DirectCast(Sub()
mailBox = comboBoxEmailFolders.SelectedValue
End Sub, Action))
allMails = MailRepo.GetAllMails(mailBox)
Catch i4e As Imap4Exception
MsgBox("Error: Folder not found" & vbCrLf & i4e.Message)
Return
End Try
Dim msg As Message
Dim msgInt As Integer = 1
'Save each message
For Each msg In allMails
bw_Save.ReportProgress(100 / allMails.Count * msgInt, Nothing)
SaveMessage(msg)
msgInt += 1
Next
End Sub
Private Sub bw_Save_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
Dim percentDone As String = e.ProgressPercentage.ToString() & "%"
updateStatus("Saving Emails " & percentDone & " done.")
progressBarStatus.Value = e.ProgressPercentage
End Sub

background worker and threads

i am using a background worker with a timer to call a function that has a for loop... as below :
Private Sub t_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles t.Tick
t.Enabled = False
t.Interval = 5000
Start()
End Sub
Sub Start()
If frm10BckWorker.IsBusy <> True Then
frm10BckWorker.WorkerReportsProgress = True
frm10BckWorker.RunWorkerAsync()
End If
End Sub
Private Sub frm2BckWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles frm10BckWorker.DoWork
StartSending()
End Sub
Sub StartSending()
Try
f.GetNumbers("JK_SP_GET_Users_TO_PROCEED", UsersBulkCnx(8))
count = f.numbersTable.Rows.Count
If count = 0 Then Exit Sub
For I = 0 To count - 1
Id = Trim(f.GetReaderValue(f.numbersTable.Rows(I).Item("ID")))
MO = Trim(f.GetReaderValue(f.numbersTable.Rows(I).Item("MO")))
FamilyName = Trim(f.GetReaderValue(f.numbersTable.Rows(I).Item("FamilyName")))
CName = Trim(f.GetReaderValue(f.numbersTable.Rows(I).Item("ContactNAme")))
ImageUrl = Trim(f.GetReaderValue(f.numbersTable.Rows(I).Item("ImageUrl")))
If Not f.InsertUsers(MO, FamilyName, CName,UsersCnx(8)) Then
PROC = -1
End If
f.DeleteBulk(Id, BulkNbrCnx(8))
f.InsertHistory(MO, FamilyName, CName,ImageUrl, UsersBulkCnx(8))
Next
Catch ex As Exception
f.WriteToText("StartSending", ex.ToString)
End Try
End Sub
what i need is to run in background this function f.InsertHistory that i call in the for loop and keep the loop running at the time without waiting for this function to end to go to the next record in the loop,
any suggestions please?

Issue with Progressbar in VB2012

I am trying to add a ProgressBar to my program. The program basically compares two values of time and when the values are equal a MessageBox appears to indicate that time is up. I need the ProgressBar to load based on the time difference of the two values. One of the values in a clock and the other is input by the user (similar to an alarm).
My code:
Imports System.Net.Mime.MediaTypeNames
Public Class Form1
Private hour As Integer = 0
Private minute As Integer = 0
Private second As Integer = 0
Public Sub show_time()
second += 1
If second = 59 Then
second = 0
minute += 1
If minute = 59 Then
minute += 1
hour += 1
End If
End If
Label3PrgressStdPC.Text = hour.ToString.PadLeft(2, "0") & ":"
Label3PrgressStdPC.Text &= minute.ToString.PadLeft(2, "0") & ":"
Label3PrgressStdPC.Text &= second.ToString.PadLeft(2, "0")
Label3PrgressStdPC.Refresh()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
show_time()
If TextBox1.SelectedText = TextBox1.Text Then Exit Sub
If TextBox1.Text = Label3PrgressStdPC.Text Then
Timer1.Stop()
MsgBox("time is up")
End If
End Sub
Private Sub Bn_start_St01_Click(sender As Object, e As EventArgs) Handles Bn_start_St01.Click
Timer1.Start()
Timer1.Enabled = True
Timer2.Start()
Timer2.Enabled = True
End Sub
**Private Sub ProgressBar1_Click(sender As Object, e As EventArgs) Handles ProgressBar1.Click
ProgressBar1.Maximum = , the max progrssbr will be determine by user input
ProgressBar1.Minimum = 0**
End Sub
**Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
progresbar1.value = ,Not so sure how to write the logic here**
End Sub
End Class
Can anyone help me out i am really getting frustrated.....thanks
How about something like this...
Private Ticker As Timer = New Timer 'Create a timer
Private Start As DateTime 'Store when we start
Private Expire As DateTime 'and when we end
'Call this to get things going
Sub Begin(EndHour As Integer, EndMinute As Integer, EndSecond As Integer)
Start = DateTime.Now
'If input is a time today ...
Expire = DateTime.Now.Date.Add(New TimeSpan(EndHour, EndMinute, EndSecond))
'or just a number of hours/mins/secs from now...
Expire = DateTime.Now.Add(New TimeSpan(EndHour, EndMinute, EndSecond))
'When the timer fires, call Tick()
AddHandler Ticker.Elapsed, Sub() Tick()
Ticker.Enabled = True
Ticker.Interval = 1000
Ticker.Start
End Sub
Private Sub Tick()
If DateTime.Now < Expire Then
'Not Finished
Dim Elapsed = DateTime.Now.Subtract(Start)
Dim TotalMillis = Expire.Subtract(Start).TotalMilliseconds
Dim ProgressDouble = Elapsed.TotalMilliseconds / TotalMillis
'Me.Invoke is used here as the timer Tick() occurs on a different thread to the
'one used to create the UI. This passes a message to the UI telling it to
'update the progress bar.
Me.Invoke(Sub()
ProgressBar1.Value = CInt(ProgressDouble * ProgressBar1.Maximum)
Label3PrgressStdPC.Text = Elapsed.ToString
End Sub)
Else
'Done
MessageBox.Show("Done")
Ticker.Stop
End If
End Sub
See VB.NET Delegates and Invoke - can somebody explain these to me? for more information on Invoking.