如何在BeginReceive()和EndReceive()函数之后清除系统内存

本文关键字:之后 清除 内存 系统 函数 BeginReceive EndReceive | 更新日期: 2023-09-27 17:50:51

我正在做一个项目,我正在使用套接字连接到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每次

如何在BeginReceive()和EndReceive()函数之后清除系统内存

从我可以告诉的问题是,你不断追加文本到你的StringBuilder实例,从来没有释放它。你的缓冲区很好,因为它只是重新使用已经分配的内存。

你可以通过设置sb.Length = 0来清除StringBuilder。在我看来,这是一个奇怪的API,我觉得应该有一个.Clear()方法。

当我通读你的代码时,我不确定为什么你有一个StringBuilder实例。它在其他地方做什么?StateObject的定义是什么?