Check Internet connection on background thread and update UI

S

salimgbelim

Hi Guys,

It seems to be a very simple thing,but unfortunately I can't succeed so
i thought to post a question to get new Ideas.

My problem is : I want a thread running in background to check wether
Internet Conection is available,if so update the property on the form
to True or else False(ideally i want a image to be updated on form
(online/offline image))

Below is my Code which nearly works but the application hangs
eventually after some time on device it works fine on emulator :-(

Any inputs or new/better way or doing this???

Regards
Salim

CODE :
-------------------------------------------------------------------------------------
Imports System
Imports System.Threading
Imports eXml.ExpenseWorld.SmartDevice.PocketPC
Imports System.Net

Public Class TimerTesting
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call
' Create the delegate that invokes methods for the timer.
Dim timerDelegate As New TimerCallback(AddressOf CheckStatus)

' Create a timer that waits one second, then invokes every
second.
Dim Timer = New Timer(timerDelegate, s, 1000, 1000)
s.tmr = Timer

End Sub

Protected Overloads Overrides Sub Dispose(ByVal disposing As
Boolean)
MyBase.Dispose(disposing)
End Sub

Private s As New TimerExampleState

'NOTE: The following procedure is required by the Windows Form
Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents Button1 As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub
InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(88, 56)
Me.Button1.Text = "Button1"
'
'TimerTesting
'
Me.ClientSize = New System.Drawing.Size(282, 270)
Me.Controls.Add(Me.Button1)
Me.Text = "TimerTesting"

End Sub

#End Region

#Region "Properties"

Private mIsconnected As Boolean
Private Property Isconnected() As Boolean
Get
Return Me.mIsconnected
End Get
Set(ByVal Value As Boolean)
Me.mIsconnected = Value
End Set
End Property

#End Region

#Region " Private sub"

Public Sub CheckStatus(ByVal state As [Object])
Dim st As TimerExampleState = CType(state, TimerExampleState)
st.counter += 1
Me.CheckConnection()
Me.Invoke(New EventHandler(AddressOf UpdateInterface))
End Sub

Private Sub UpdateInterface(ByVal sender As Object, ByVal e As
System.EventArgs)
'If Me.mIsconnected = False Then
' Me.mOnlineStatus.Online = False
' Me.mOnlineStatus.Update()
' MessageBox.Show(mLength.ToString)
'Else
' Me.mOnlineStatus.Online = True
' Me.mOnlineStatus.Update()
'End If
End Sub

Private Function CheckConnection() As Boolean
If Me.IsCConnected() = True Then
Me.mIsconnected = True
Else
Me.mIsconnected = False
End If
End Function

Public Function IsCConnected() As Boolean

Dim hwrRequest As HttpWebRequest
Dim hwrResponse As HttpWebResponse

Dim strUrl As String = "http://www.google.com/"
Dim bConnected As Boolean = False

Try
hwrRequest = CType(WebRequest.Create(strUrl),
HttpWebRequest)
hwrResponse = CType(hwrRequest.GetResponse(),
HttpWebResponse)
hwrRequest.Abort()

If hwrResponse.StatusCode = HttpStatusCode.OK Then
If hwrResponse.ContentLength <= 0 Then
bConnected = False
Else
bConnected = True
End If
End If
hwrResponse.GetResponseStream.Close()
Catch we As WebException
bConnected = False
Catch ex As Exception
bConnected = False
Finally
hwrRequest = Nothing
hwrResponse = Nothing
End Try

Return bConnected

End Function

#End Region

#Region "Event Handler - Button"

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
If Me.mIsconnected = True Then
MessageBox.Show("Online")
Else
MessageBox.Show("Offline")
End If
End Sub

#End Region

#Region "Private Class"

Class TimerExampleState
Public counter As Integer = 0
Public tmr As Timer
End Class

#End Region

End Class

END CODE :
-------------------------------------------------------------------------------------
 
D

Daniel Moth

Some suggestions

0. If a method does not return anything, make it a Sub not a Function
1. Turn Option Strict On
2. Do not start a threading timer at creation rather pass -1 as the timeout.
When you start it, do so with the Change method.
3. Never use the interval. I.e. the second parameter of the constructor and
the Change method is always -1; this avoids reentrancy.
4. Following from point 3, when the timer calls you back and only at the
very end of the method, call Change again thus running the timer again (if
you need to run it).
5. If the webresponse.statuscode is OK, there should be no point checking
the contentlength; you can connect.

Cheers
Daniel
--
http://www.danielmoth.com/Blog/


salimgbelim said:
Hi Guys,

It seems to be a very simple thing,but unfortunately I can't succeed so
i thought to post a question to get new Ideas.

My problem is : I want a thread running in background to check wether
Internet Conection is available,if so update the property on the form
to True or else False(ideally i want a image to be updated on form
(online/offline image))

Below is my Code which nearly works but the application hangs
eventually after some time on device it works fine on emulator :-(

Any inputs or new/better way or doing this???

Regards
Salim

CODE :
-------------------------------------------------------------------------------------
Imports System
Imports System.Threading
Imports eXml.ExpenseWorld.SmartDevice.PocketPC
Imports System.Net

Public Class TimerTesting
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call
' Create the delegate that invokes methods for the timer.
Dim timerDelegate As New TimerCallback(AddressOf CheckStatus)

' Create a timer that waits one second, then invokes every
second.
Dim Timer = New Timer(timerDelegate, s, 1000, 1000)
s.tmr = Timer

End Sub

Protected Overloads Overrides Sub Dispose(ByVal disposing As
Boolean)
MyBase.Dispose(disposing)
End Sub

Private s As New TimerExampleState

'NOTE: The following procedure is required by the Windows Form
Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents Button1 As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub
InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(88, 56)
Me.Button1.Text = "Button1"
'
'TimerTesting
'
Me.ClientSize = New System.Drawing.Size(282, 270)
Me.Controls.Add(Me.Button1)
Me.Text = "TimerTesting"

End Sub

#End Region

#Region "Properties"

Private mIsconnected As Boolean
Private Property Isconnected() As Boolean
Get
Return Me.mIsconnected
End Get
Set(ByVal Value As Boolean)
Me.mIsconnected = Value
End Set
End Property

#End Region

#Region " Private sub"

Public Sub CheckStatus(ByVal state As [Object])
Dim st As TimerExampleState = CType(state, TimerExampleState)
st.counter += 1
Me.CheckConnection()
Me.Invoke(New EventHandler(AddressOf UpdateInterface))
End Sub

Private Sub UpdateInterface(ByVal sender As Object, ByVal e As
System.EventArgs)
'If Me.mIsconnected = False Then
' Me.mOnlineStatus.Online = False
' Me.mOnlineStatus.Update()
' MessageBox.Show(mLength.ToString)
'Else
' Me.mOnlineStatus.Online = True
' Me.mOnlineStatus.Update()
'End If
End Sub

Private Function CheckConnection() As Boolean
If Me.IsCConnected() = True Then
Me.mIsconnected = True
Else
Me.mIsconnected = False
End If
End Function

Public Function IsCConnected() As Boolean

Dim hwrRequest As HttpWebRequest
Dim hwrResponse As HttpWebResponse

Dim strUrl As String = "http://www.google.com/"
Dim bConnected As Boolean = False

Try
hwrRequest = CType(WebRequest.Create(strUrl),
HttpWebRequest)
hwrResponse = CType(hwrRequest.GetResponse(),
HttpWebResponse)
hwrRequest.Abort()

If hwrResponse.StatusCode = HttpStatusCode.OK Then
If hwrResponse.ContentLength <= 0 Then
bConnected = False
Else
bConnected = True
End If
End If
hwrResponse.GetResponseStream.Close()
Catch we As WebException
bConnected = False
Catch ex As Exception
bConnected = False
Finally
hwrRequest = Nothing
hwrResponse = Nothing
End Try

Return bConnected

End Function

#End Region

#Region "Event Handler - Button"

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
If Me.mIsconnected = True Then
MessageBox.Show("Online")
Else
MessageBox.Show("Offline")
End If
End Sub

#End Region

#Region "Private Class"

Class TimerExampleState
Public counter As Integer = 0
Public tmr As Timer
End Class

#End Region

End Class

END CODE :
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top