0

我正在使用 TCP 套接字将每个大约 10 Mbs 的文件从 pc 发送到电话。在电话端,我收到这样的数据:

  Dim B As Byte() = New Byte(Socket.ReceiveBufferSize - 1) {}
  Me.Args.SetBuffer(B, 0, Socket.ReceiveBufferSize)
  Me.Socket.ReceiveAsync(Me.Args)

ReceiveBufferSize 属性设置为 30000000。这就是我阅读它的方式:

 Dim R As Byte() = New Byte(Me.Args.BytesTransferred - 1) {}
 Dim s As New MemoryStream(Me.Args.Buffer)
 Me.Args.SetBuffer(0, 0)

 s.Read(R, 0, ntpData.Length)
 s.Dispose()

此过程需要大量内存(约 300Mbs),因此我无法在内存使用限制为 180Mbs 的低价设备上运行该应用程序。.Dispose()每次电话接收到某些东西时,我都无法使用套接字,因为它会引发 OjbectDisposed 异常。如何释放内存?

4

3 回答 3

1

It sounds like the question could possibly be turned around. How can you use less memory? For instance you could:

  • download the data in smaller chunks from the socket and reuse the same buffer rather than reallocating it.
  • write the data to an Isolated Storage stream rather than memory, and only load into memroy what you need to show in the app at a given point in time.

(this would be dependent on the exact scenario you are working in)

You should also make sure that the memory you have already allocated is garbage collected once you are done with it by making sure that nothing is holding a reference to it

Also, have you profiled the app to confirm that it really is this socket memory that is causing the problem or is it actually due to some other memory elsewhere?

于 2013-05-02T10:22:07.963 回答
0

你很幸运,因为你在开发阶段就失去了记忆。

从不,曾经在 windows Phone 上使用大于 84KB 的缓冲区(字节数组),GC 不会收集大于 84KB 的字节数组中的数据。

您的代码应类似于:

Try
            stream.Position = 0
            Dim totalRead As Long = 0
            Dim readBuffer As Integer
            Dim bufferSize As Long = 4096 'under 86KB
            Dim readArray = New Byte(bufferSize - 1) {}
            While totalRead < stream.Length
                readBuffer = Await stream.ReadAsync(readArray, 0, bufferSize)
                totalRead += readBuffer
                'Use readArray here
            End While
            stream.Dispose()
        Catch ex As Exception
            'Log My exception
        Finally
            stream.Dispose()
        End Try

只需尝试更改与此类似的代码,您就不会超过 50MB RAM

祝你好运。

于 2013-05-03T11:52:07.967 回答
0

由于我找不到任何真正解决问题的方法,因此我设法使用解决方法来解决。

每个数据包都标有一个标头。在发送大量数据之前,我向客户端发送了一个带有不同标头的数据包。然后客户端识别出这种类型的标题并读取标题旁边的字节:它们包含下一个流的长度。所以客户端设置缓冲区长度并等待数据到来。

于 2013-05-05T10:08:38.583 回答