Hi all.
I have a Windows Service that has to poll several devices every 5 seconds. The devices run an embedded version of Linux running an application that responds to the poll through a TCP/IP connection.
I use threads to be able to poll all the devices without hanging the service, that does several other things ath the same time.
The problem is: I have a memory leak when some of devices are off-line. The TcpClient connection will fail and the memory used by the service starts to increase until it raises an OutOfMemory exception and the service stops working when it reaches about 40MB of used memory.
That's how I call the threads to poll the devices:
Try
Dim i As Integer
i = dsContr.Tables.Count
Dim oDwnlMsg(i) As clControllerPoll
Dim tPollCont(i) As Thread
For i = 0 To i - 1
If _TCPServerHw Is Nothing Then
Exit Sub
End If
Dim _IPAddress As String = CStr(dsContr.Tables(i).Row
s(0).Item(
"IPAddress
"))
oDwnlMsg(i) = New clControllerPoll
oDwnlMsg(i).IPAdr = _IPAddress
tPollCont(i) = New Thread(AddressOf oDwnlMsg(i).SendPollingMsg
)
tPollCont(i).IsBackground = True
tPollCont(i).Start()
Next
Catch ex As Exception
WriteToLogFile(ex, GetCurrentMethod.Name)
End Try
And this is the method that tries to send the polling message. If it fails, it returns Nothing. If not, it returns a string sent by the device.
Public Function SendStringMessage(ByVal Message As String, Optional ByVal ControlTimeout As Boolean = False) As String
Try
_TCPClient = New TcpClient(_RemoteHost, _RemotePort)
_NetworkStream = _TCPClient.GetStream()
If ControlTimeout Then
_NetworkStream.WriteTimeou
t = 2000
_NetworkStream.ReadTimeout
= 2000
End If
Dim strResponse As String
'Send a string (newline terminated) to the server.
Dim writer As New System.IO.StreamWriter(_Ne
tworkStrea
m)
Dim reader As New System.IO.StreamReader(_Ne
tworkStrea
m)
writer.Write(Message)
writer.Flush()
'Read server response (up to a newline).
Try
strResponse = reader.ReadLine
Catch ex As Exception
Console.WriteLine("TCP READ ERROR: " & ex.Message)
strResponse = Nothing
Finally
'Close
writer.Close()
reader.Close()
_NetworkStream.Close()
End Try
Return strResponse
Catch ex As Exception
Console.WriteLine("TCP SendStringMessage ERROR: " & ex.Message)
Return Nothing
Finally
If Not _NetworkStream Is Nothing Then
_NetworkStream.Close()
_NetworkStream.Dispose()
_NetworkStream = Nothing
End If
If Not _TCPClient Is Nothing Then
_TCPClient.Close()
_TCPClient = Nothing
End If
End Try
End Function
I believe it has something to do with the TCP timeout that takes longer that the next polling message (every 5s).
Any help is appreciated.
Start Free Trial