我正在做一个项目,我使用socket连接到USSD服务器。该项目是一个实时和24小时运行的调度程序。
以下是我的BeginReceive()
和EndReceive()
Public Sub Receive(ByVal client As Socket)
Dim state As New StateObject
state.workSocket = client
Try
If m_clientSocket.Connected Then
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)
Else
Connect()
End If
Catch se As SocketException
logstr = se.Message
write_log(logstr, "Receive", "Receive")
End Try
End Sub
Public Sub ReceiveCallback(ByVal ar As IAsyncResult)
Dim state As StateObject = CType(ar.AsyncState, StateObject)
Dim client As Socket = state.workSocket
Dim receiveData As String = ""
Dim sendData As String = ""
Dim bytesRead As Integer = client.EndReceive(ar)
If bytesRead > 0 Then
state.sb.Append(System.Text.Encoding.ASCII.GetString(state.buffer, 0, bytesRead))
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)
receiveData = state.sb.ToString()
Me.lsBulk.Items.Insert(0, receiveData)
sendData = getReply(receiveData)
write_log(Now.ToString & " : " & receiveData & vbCrLf, "bytesRead", "bytesRead")
Try
Dim objData As [Object] = sendData
Dim byData As Byte() = System.Text.Encoding.ASCII.GetBytes(objData.ToString())
If m_clientSocket IsNot Nothing Then
m_clientSocket.Send(byData)
End If
write_log(Now.ToString & " : " & sendData & vbCrLf, "sendData", "sendData")
Catch se As SocketException
logstr = se.Message
write_log(logstr, "WaitForData", "waitfordata")
End Try
Else
receiveData = state.sb.ToString()
If receiveData <> "" Then
write_log(Now.ToString & " : " & receiveData & vbCrLf, "receiveData2", "receiveData2")
End If
End If
End Sub
问题是这个程序占用了我很多的记忆。第一次运行后它需要3.5GB然后一小时后它需要4.5GB,依此类推,直到或除非我们重启它。它正在成为服务器的一大麻烦,因为它在内存中分配了大量空间。
我无法理解我必须清除缓冲区以释放系统内存。每次写入数据库时,缓冲区中的数据都不需要保留。
我想提一下,每次缓冲区大小为10024。
答案 0 :(得分:1)
据我所知,问题是你不断在你的StringBuilder
实例中附加文本而从不发布它。你的缓冲区很好,因为它只是重新使用已经分配的内存。
您只需设置sb.Length = 0
即可清除StringBuilder。在我看来,这是一个奇怪的API,我觉得应该有.Clear()
方法。
当我读完你的代码时,我不确定为什么你有一个StringBuilder实例。它在其他地方做了什么? StateObject
的定义是什么?