VB.Net - Timer Control freezes application - vb.net

I have added a Timer control to a vb.net application that is used to check if a website is up or down. There are two Timer controls in the app. Both are from System.Windows.Forms.Timer.
There is Timer1 and Timer2. Timer1 is used to perform the website check. Timer2 is simply to display a current date and time in the ToolStrip at the base of the form. The Timer2 runs without issue displaying the time, but when I start the website check that runs Timer1, the application freezes after two checks. Sometimes it runs longer, but eventually freezes.
I have to End Task from within Task Manager in order to shut down the application. I have tested this from within the Debugger and after running the executable. I have also completely removed Timer2 and tested, but the freezing remains. Here is my code. Any assistance would be greatly appreciated.
Imports System
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
lblStatus.Text = ""
Timer1.Stop()
btnStart.Enabled = True
btnStop.Enabled = False
End Sub
Public Function CheckAddress(ByVal URL As String) As Boolean
Try
Dim request As WebRequest = WebRequest.Create(URL)
Dim response As WebResponse = request.GetResponse()
Catch ex As Exception
Return False
End Try
Return True
End Function
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
Dim startPoint As Integer = -1
If CheckAddress(txtAddress.Text).ToString() = True Then
rtxtResults.AppendText(" -- " & txtAddress.Text & " - Website shows UP at " & tsClock.Text & " - " & vbNewLine)
ElseIf CheckAddress(txtAddress.Text).ToString() = False Then
rtxtResults.AppendText(" -- " & txtAddress.Text & " - Website shows DOWN at " & tsClock.Text & " - " & vbNewLine)
End If
Do
startPoint = rtxtResults.Find("Website shows DOWN at", startPoint + 1, RichTextBoxFinds.None)
If (startPoint >= 0) Then
rtxtResults.SelectionStart = startPoint
rtxtResults.SelectionLength = "Website shows DOWN at".Length
rtxtResults.SelectionColor = Color.Red
End If
Loop Until startPoint < 0
End Sub
Private Sub Timer2_Tick(sender As System.Object, e As System.EventArgs)
tsClock.Text = Now()
End Sub
Private Sub btnStart_Click(sender As System.Object, e As System.EventArgs) Handles btnStart.Click
If txtInterval.Text = "" Then
MsgBox("Must enter a number")
Exit Sub
End If
lblStatus.ForeColor = Color.Green
lblStatus.Text = "Running"
btnStart.Enabled = False
btnStop.Enabled = True
Timer1.Interval = Int(txtInterval.Text) * 1000
Timer1.Start()
End Sub
Private Sub btnStop_Click(sender As System.Object, e As System.EventArgs) Handles btnStop.Click
lblStatus.ForeColor = Color.Red
lblStatus.Text = "Stopped"
btnStop.Enabled = False
btnStart.Enabled = True
Timer1.Stop()
End Sub
End Class

Your application's UI will "freeze" until the Timer1_Tick method completes. Most likely your Timer1_Tick's Do...Loop is not exiting. Try deleting the Do and Loop lines.

Related

opendialog to show a file and save it with checkbox vb.net

I'm trying to connect to a database (mdb file of my choice) in a login screen and i want to save it for faster logon next times i boot the software.
I click on choose database button, opendialog lets me choose the file, i click OK and the db location shows in a textbox.
there's a checkbox beneath to save it before i connect to it.
But i can't manage to keep the checkbox checked, nor the textbox filled after i restart te program.
here's my current code:
Public Class LoginScreen
Private Sub Loginscreen_load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ProgressBar2.Minimum = 0
ProgressBar2.Maximum = 100
ProgressBar2.Visible = False
Panel1.Visible = False
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Application.Exit()
End Sub
Private Sub btnExit2_Click(sender As Object, e As EventArgs) Handles btnExit2.Click
Application.Exit()
End Sub
Private Sub tmrLogin_Tick(sender As Object, e As EventArgs) Handles tmrLogin.Tick
ProgressBar2.Value = ProgressBar2.Value + 20
lblLoginMessages.Text = ProgressBar2.Value & "%" & " Completed"
If ProgressBar2.Value >= 100 Then
tmrLogin.Enabled = False
If txtUser.Text = "azert" And txtPassword.Text = "azert" Then
ProgressBar2.Value = 0
Else
lblLoginMessages.Text = "Wrong credentials, Try again!"
pboxClosed.Visible = True
PboxOpen.Visible = False
ProgressBar2.Value = 0
txtPassword.Text = ""
txtUser.Text = ""
End If
End If
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
ProgressBar2.Visible = True
tmrLogin.Enabled = True
pboxClosed.Visible = False
PboxOpen.Visible = True
''navraag doen om dit correct in te stellen! ! ! ! !!
'If ProgressBar2.Value = 100 Then
'lblLoginMessages.Text = "Logging in..."
Me.Hide()
Mainscreen.Show()
'End If
If chkSavePassword.Checked = True Then
My.Settings.databaselocation = txtDatabaselocationshow.Text
My.Settings.SaveLocation = True
End If
End Sub
Private Sub btnDBConnect_Click(sender As Object, e As EventArgs) Handles btnDBConnect.Click
If Panel1.Visible = False Then
Panel1.Visible = True
Else
Application.Exit()
End If
End Sub
Private Sub btnChoose_Click(sender As Object, e As EventArgs) Handles btnChoose.Click
Dim strtext As String
OpenFileDialog1.Filter = "Database Files | *.mdb"
OpenFileDialog1.InitialDirectory = "F:\GoogleDrive\EINDWERK VBNET"
OpenFileDialog1.Title = "Choose your Database"
OpenFileDialog1.ShowDialog()
strtext = OpenFileDialog1.FileName
txtDatabaselocationshow.Text = strtext
'If OpenFileDialog1.ShowDialog = DialogResult.OK Then
' strtext = OpenFileDialog1.FileName
' txtDatabaselocationshow.Text = strtext
'Else
' MsgBox("Error: the database file could not be read, try again.")
'End If
End Sub
Private Sub tmrshowloginpanel_Tick(sender As Object, e As EventArgs) Handles tmrshowloginpanel.Tick
Panel1.Width += 5
If Panel1.Width >= 700 Then
tmrshowloginpanel.Stop()
End If
End Sub
End Class
i've scoured the net but can't really find what to do?
if you need more information, shoot!
Walk through this with me:
Make a new project, one form, add a textbox and a combobox.
Click the textbox:
In the properties grid at the top click (Application Settings), then the 3 dots next to Property Binding. Scroll to Text. Drop down the setting and choose New at the bottom.
Give it a name of ChosenDatabasePath or something useful and descriptive like that
Repeat from "Click the textbox" for the checkbox instead, and this time bind the Checked property not the Text property.. Call the checkbox's Checked binding SavePassword or similar
Close all the dialogs so you're back at the form
Click anywhere on the background of the form when switch to Events in the property grid, find FormClosing and double click it
Put My.Settings.Save() in the FormClosing event handler
Run the app, write something in the textbox, close the form (by the X, not by stopping debugging), then immediately open the app again (run it)

vb.net backgroundworker CancelAsync not work

I have a stop problem in the backgroundworker, I use the following commands for backgroundworker:
update codes
Private Sub UnpackSystem_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles UnpackSystem.DoWork
Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
For i As Integer = 1 To 100
If worker.CancellationPending Then
e.Cancel = True
Exit For
End If
worker.ReportProgress(i, i & " iterations complete")
Threading.Thread.Sleep(250)
Dim oProcess As New Process()
Dim oStartInfo As New ProcessStartInfo("cmd.exe", "/c bin\Imgtool\simg2img.exe tmp/system.img tmp/system.img.ext4")
oStartInfo.WindowStyle = ProcessWindowStyle.Hidden
oStartInfo.CreateNoWindow = True
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
Dim sOutput As String
Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
sOutput = oStreamReader.ReadToEnd()
End Using
TextBox8.Invoke(Sub() TextBox8.AppendText(Environment.NewLine & sOutput))
Next i
End Sub
Private Sub UnpackSystem_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles UnpackSystem.ProgressChanged
Me.ProgressBar5.Value = e.ProgressPercentage
End Sub
Private Sub UnpackSystem_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles UnpackSystem.RunWorkerCompleted
If e.Cancelled = True Then
TextBox8.AppendText(Environment.NewLine & "Canceled!")
ElseIf e.Error IsNot Nothing Then
TextBox8.AppendText(Environment.NewLine & "Error: " & e.Error.Message)
Else
TextBox8.AppendText(Environment.NewLine & "Done!")
End If
End Sub
and, I use the following code to stop backgroundworker proccess ...
Private Sub Button55_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles Button55.Click
If Me.UnpackSystem.IsBusy Then
Me.UnpackSystem.CancelAsync()
End If
Dim cmd() As Process
cmd = Process.GetProcessesByName("cmd")
If cmd.Count > 0 Then
Process.GetProcessesByName("cmd")(0).Kill()
End If
End Sub
But it not be canceled, Where is my problem?
You are only testing whether a cancellation is pending when the DoWork event handler first starts, which of course it will not be at that stage. In order for the background task to be cancelled later on, you would have to actually test whether a cancellation is pending later on.
There's no magic here though. As I said, in order to cancel, you have to actually test whether a cancellation is pending within the DoWork event handler. That test can only come between other lines of code. Once you call that ReadToEnd method, you are going to read the stream to the end, whether the user has requested cancellation or not. You obviously can't test for a pending cancelation until that call returns

BackgroundWorker not updating GUI at other Form

As stated I have a BackgroundWorker that runs a sub function DoHeavyWork().
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
Else
'DO HEAVY WORK
DoHeavyWork()
End If
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ProgressBar1.Value = e.ProgressPercentage
Label8.Text = e.ProgressPercentage.ToString() + " %"
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled = True Then
ProgressBar1.Value = 0
Label8.Text = ""
ElseIf e.Error IsNot Nothing Then
MessageBox.Show(e.Error.Message)
Else
MessageBox.Show("Completed!")
End If
End Sub
Inside this sub function DoHeavyWork(), there are codes to update another form's GUI.
Private Sub DoHeavyWork()
For i As Integer = 1 To fresult_counter
Dim fresult As New Button
fresult.Name = "fresult_" & i
fresult.Text = result(index_acc(i - 1)).ToString
fresult.TextAlign = ContentAlignment.MiddleLeft
fresult.Width = 265
fresult.AutoSize = True
fresult.BackColor = Color.White
With fresult.FlatAppearance
.BorderColor = Color.White
.BorderSize = 2
.MouseDownBackColor = Color.DeepSkyBlue
.MouseOverBackColor = Color.DeepSkyBlue
End With
fresult.Anchor = AnchorStyles.Left
fresult.FlatStyle = FlatStyle.Flat
fresult.UseVisualStyleBackColor = False
fresult.Location = New Point(0, 22 * (i - 1))
Form1.TabControl2.TabPages(1).Controls.Add(fresult)
BackgroundWorker1.ReportProgress(i)
Next
End Sub
The problem is it did not update the GUI but the progress bar is working. I've tried getting the set of code out of the BackgroundWorker and it works fine. Is there something I did not set to enable BackgroundWorker to update the GUI?
As mentioned by jmcilhinney, the solution for my answer is very simple.
Just let the BackgroundWorker update the progress bar at the background. And when it finished doing it's work, the progress bar will be at 100 which means it is completed.
Once it is completed, simply add the update GUI codings (in my case: 'Form1.TabControl2.TabPages(1).Controls.Add(fresult)') at the sub function when BackgroundWorker has completed:
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled = True Then
ProgressBar1.Value = 0
Label8.Text = ""
ElseIf e.Error IsNot Nothing Then
MessageBox.Show(e.Error.Message)
Else
MessageBox.Show("Completed!")
Form1.TabControl2.TabPages(1).Controls.Add(fresult)
End If
End Sub

vb.net background worker cancel not working

I'm having an issue where BackgroundWorker.CancelAsync() isn't working. I have WorkerSupportsCancellation set to TRUE. I am also polling BackgroundWorker1.CancellationPending in DoWork. Here is sample code of what I am trying to achieve. I have background worker looping through a time stamp and assigning a value to Measurement variable. I have a subroutine that queries the last reported Measurement variable and writes to listbox. After 5 loops I send BackgroundWorker.CancelAsync(). I can see the cancellation is pending, but it doesn't actually cancel the background worker. Is this a race condition?
Public Class Form1
Dim Measurement As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
Delay(0.5)
For x = 1 To 5
ListBox1.Items.Add(Measurement)
ListBox1.TopIndex = ListBox1.Items.Count - 1
TextBox1.Text = BackgroundWorker1.CancellationPending
Delay(1)
Next
BackgroundWorker1.CancelAsync()
TextBox1.Text = BackgroundWorker1.CancellationPending
ListBox1.Items.Add("Cancel Pend: " & BackgroundWorker1.CancellationPending)
Delay(5)
ListBox1.Items.Add("Busy: " & BackgroundWorker1.IsBusy)
End Sub
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
BackgroundWorker1.Dispose()
Exit Sub
Else
Do
Measurement = Now()
Loop
End If
End Sub
End Class
You just need to move the check for the cancellation inside the Do...Loop otherwise it will be tested only at the start of the DoWork event handler and never after that
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
BackgroundWorker1.Dispose()
Else
Do
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
BackgroundWorker1.Dispose()
Exit Do
Else
Measurement = Now()
End If
Loop
End if
End Sub

Cancelling upload with WebClient?

Using the following VB.Net simple code to upload files in FTP, a call to WebClient.CancelAsync() doesn't actually cancel the upload.
Does someone know why, and what can be done about this?
Private Sub UploadProgressChanged(ByVal sender As Object, ByVal e As System.Net.UploadProgressChangedEventArgs)
'TO-DO: Why is pbar empty?
ProgressBar1.Value = e.ProgressPercentage
Label1.Text = e.BytesSent & " bytes sent"
End Sub
Private Sub UploadFileCompleted(ByVal sender As Object, ByVal e As System.Net.UploadFileCompletedEventArgs)
MessageBox.Show("Done!")
Button1.Text = "Upload"
ProgressBar1.Value = 0
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim client As New WebClient
If Button1.Text = "Cancel" Then
'TO-DO: Doesn't actually cancel upload!
client.CancelAsync()
Button1.Text = "Upload"
ProgressBar1.Value = 0
Else
Button1.Text = "Cancel"
Const MYFILE = "big.file.bin"
Const LocalFile As String = "C:\" & MYFILE
Dim RemoteFile As String = "ftp://upload.acme.com/" & MYFILE
client.Credentials = New NetworkCredential("anonymous", "test")
client.Proxy = Nothing
AddHandler client.UploadFileCompleted, AddressOf UploadFileCompleted
AddHandler client.UploadProgressChanged, AddressOf UploadProgressChanged
ProgressBar1.Maximum = 100
Try
client.UploadFileAsync(New Uri(RemoteFile), LocalFile)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
client.Dispose()
End If
End Sub
Thank you.
I don't use VB myself but it looks to me like you are calling client.cancelAsync() on the wrong client.
You are making a new client each time you press the cancel/upload button.
If you want to cancel the first client you started you need to instantiate it externally to the click_handler.
Also why are you using the button label to check if the client should be cancelled?
You can do if client.IsBusy ...