2016-07-28 30 views
-1

此功能內存不足錯誤與RETURN語句,GetString的調用內存不足錯誤的Encoding.UTF8.GetString

Public Function UnzipString(ByVal bByteBuffer() As Byte) As String 

    Dim lastBytes(3) As Byte 

    Array.Copy(bByteBuffer, bByteBuffer.Length - 4, lastBytes, 0, 4) 
    Dim sBufferLength As Integer = BitConverter.ToInt32(lastBytes, 0) 

    Dim sBuffer(sBufferLength - 1) As Byte 
    Dim ms As New System.IO.MemoryStream(bByteBuffer) 
    Dim ds As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress, True) 
    ds.Read(sBuffer, 0, sBufferLength) 
    Return System.Text.Encoding.UTF8.GetString(sBuffer) 

End Function 

停止。 sBuffer非常大,其中有165 MB(字節)數據,但我仍然喜歡它的工作。任何人都可以想出一種讓它適用於大型數據集的方法嗎?

+1

你真的需要在一個單一的通話整個字符串?你打算用它做什麼?創建一個StreamReader通常會更好。請注意,您當前的代碼已損壞,因爲您忽略了'Stream.Read'返回的值......它可能不會在一次調用中讀取所有內容。 –

+0

它是在第一次調用方法時重現的,還是被多次調用?它是以32或64位進程運行嗎?失敗時進程正在使用多少內存? –

+0

它是一個64位進程,主機EXE(服務)在20GB機器上使用的內存大約爲1GB。 sBufferLength是165,744,584。在這種情況下,字符串隨後被寫入文件,但是這個子文件也用於解壓其他字符串。代碼已經生產了好幾年,從未出錯,所以我不認爲它已經破產,但我認爲它有可能打破。我可以使用sBuffer並直接將其寫入文件的解決方案,但實際上它會與UTF8.GetString調用的效果相同嗎? – user2728841

回答

0

我結束了寫另一子的字節數組寫入直接到一個文件中,這樣就避免了整個解壓內容的任何內存存在:

Public Sub UnzipStringToFile(bByteBuffer() As Byte, sFileName As String) 

    ' This avoids the "out of memory" error when using UnzipString 

    Using _ 
     ms As New System.IO.MemoryStream(bByteBuffer), 
     ds As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress, True), 
     fs As System.IO.FileStream = System.IO.File.Create(sFileName) 

     ds.CopyTo(fs) 
     ds.Close() 

    End Using 

End Sub