2015-08-03 96 views
-2

我正嘗試動態生成大量(> 5000)的pdf文檔。問題是在pdf生成過程中,我收到了內存不足異常。我決定將我的5000頁PDF分成更小的500頁pdf,但是當我嘗試這種方式時.net仍然使用相同的內存。有沒有辦法強制我的應用程序釋放一個變量仍在使用的未使用內存?這裏是導致問題的代碼如何強制.net以釋放內存?

For Each patronRow As DataRow In patronsDatatable.Rows 
.....some other code 
         If FARPrintOneLetterPerStudent = False Then 
         If farApplicationID <> _previousFarApplicationID Or _firstapp = True Then 
          lettercount = lettercount + 1 
          '************* test code ***************** 
          If lettercount = 500 Then 
           If Me._printLabels = False Then 
            FixEndPdf(finalpdf) 
           End If 
           ' Export moved from dataprovider 
           smallpdfcount = smallpdfcount + 1 
           ExportToPdf(ImportRtf(finalpdf), smallpdfcount) 
           finalpdf = Nothing 
           _isfirst = True 
           lettercount = 0 
          Else 
           If lettercount < 500 Then ' we only need to add to this variable when there is less than 500 pages 
            finalpdf = AddtoletterPdf(letterBody, printmultiple) 
            '_previewpdf = finalpdf 
           End If 
           _previousFarApplicationID = farApplicationID 
           _firstapp = False 
          End If 
         End If 
        Else 
         finalpdf = AddtoletterPdf(letterBody, printmultiple) 
        End If 
         'create a record in LettersDatatable for POS and FAR letters 
         AddToLettersDataTable(letterBody, patronID, patronName, farApplicationID, headerImageBuffer) 
        Else 
         'Create a record in labels datatable 
         AddToLabelsDatatable(letterBody, patronName, patronID, farApplicationID) 
        End If 
       End If 
     Next 



    Public Function ImportRtf(ByVal content As String) As RadDocument 
    Dim provider As New RtfFormatProvider() 
    Try 
     Return provider.Import(content) 
    Catch ex As Exception 
     MessageBox.Show("Error in Import to Pdf") 
    End Try 
End Function 

    Public Sub ExportToPdf(ByVal document As RadDocument, smallpdfcount As Integer) 
    Dim provider As New PdfFormatProvider 
    Dim OneSourceFolder As String = GetInstallFolder() 
    Try 
     Using output As Stream = File.Create(OneSourceFolder & "\letter" & smallpdfcount & ".pdf") 
      'Using output As Stream = File.Create(OneSourceFolder & "\letter.pdf") 
      provider.Export(document, output) 
     End Using 
    Catch ex As Exception 
     MessageBox.Show("Error in ExporttoPdf") 
    End Try 
+0

可以調用垃圾收集器的方式GC.Collect()...可能在生成每個PDF後可以調用它... – lem2802

+0

您如何知道內存實際上未被使用? –

+1

這是關於託管代碼嗎? – Hristo

回答

3

我不認爲問題是.net保留未使用的內存。如果.net在內存中運行較少,則無論發生什麼情況,都會觸發垃圾回收。由於這不是你的情況,我想真正的問題是你保持對你想要從內存中獲取的對象的引用。

所以你應該看看什麼是:

  • 使用多少內存哪些對象?
  • 這些對象是否永久存儲在內存中的任何位置?尋找任何保持對你的對象的引用的集合。
  • 是否有任何實現IDisposable接口的對象未正確放置? (通過調用Dispose()或由Using塊。
  • 是否有任何MemoryStream S或任何寫入到周圍的硬盤是沒有正確關閉?
  • 你清除引用到源對象用於填充一旦你的PDF文件,與他們做了什麼?
  • 你使用任何緩存,可以填補?

希望,讓你開始尋找。調用GC.Collect()迫使垃圾收集的地方通常是錯誤的方式,因爲.NET應該正確處理。