开发者

Saving a PDF document seems to be keeping a reference in memory (VB.NET)

I have a VB.NET user control that is saving a PDF document and then displaying that in a WebBrowser control. The code looks like this:

Using myPdfDoc As New FileStream开发者_如何学JAVA(fileName, FileMode.Create)
    Dim byt As Byte() = comLib.GetData();
    If Not byt Is Nothing Then                        
        myPdfDoc.Write(byt, 0, byt.Length)
        myPdfDoc.Flush()
        myPdfDoc.Close()

        webBrowserCtl.Navigate(fileName)
    End If
End Using

comLib is a COM interop library, written in VB6 that obtains the relevant data.

As far as I can tell, this code is keeping a reference to the PDF document (as VB.NET does not close when the program finishes). I found this article which seems to imply that adobe doesn't clean up after itself properly, but implementing its suggested changes doesn't seem to help.

Why might I be getting this behaviour? In VB6, a program not closing properly was always a result of stray object references that are not cleared up. Is this still true in VB.NET? If so, what can I do to identify which object, or why this might be happening?


I would separate this out: reading the data, writing the data, and viewing the data:

Dim byt As Byte() = Nothing
Try
  byt = comLib.GetData()
Finally
  If Not comLib Is Nothing Then
    Marshal.ReleaseComObject(comLib)
  End If
End Try

If Not byt Is Nothing Then
  Using myPdfDoc As New FileStream(fileName, FileMode.Create)
    myPdfDoc.Write(byt, 0, byt.Length)
  End Using

  Using webBrowserCtl As New WebBrowser()
    webBrowserCtl.Navigate(fileName)      
  End Using
End If  

The Marshal.ReleaseComObject call in the Finally ensures that the reference count is always decremented. The Flush and Close are not necessary, as Dispose will do this anyway. The WebBrowser control implements IDisposable, so I have used a Using block for that too.


You are doing something way more complicated than what I have done in the past. But I can tell you that PDF byte objects in .NET can chew up extremely large amounts of memory (even if disposed). I'd suggest using temp files on your file server (in an actual directory on the machine running your web server). Rather than keeping the objects in memory. I know the assembly PDFSharp has some good (and free) code you can use. But I do not know what would prevent your program from exiting. Good luck to you buddy.

PS: You may want to try calling the garbage collector on your own. And you should be able to see your threads in Visual Studio. When you attach to your w3wp.exe (IIS 7 process in Windows 7) process, you will get a context menu (Debug->Windows->Threads). Although I don't know if a COM thread would show in there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜