2015-08-03 94 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应该正确处理。