问题:如果我使用大 PDF 文件(50Mb,1500 页)异步调用 LoadFile() 几次(10-20 次就足够了),那么我很快就会得到 OutOfMemory 异常。如果我在 EndInvoke() 之后调用 GC.Collect() ,那么它可以解决问题。
同步调用效果很好(不会发生内存泄漏)。
关于如何在不直接调用 GC.Collect() 的情况下解决它的任何想法?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Open_Click(object sender, EventArgs e)
{
MethodInvoker invoker = this.LoadFile;
AsyncCallback callback = CallBack;
invoker.BeginInvoke(callback, null);
// Synchronous call.
// LoadFile();
}
private void CallBack(IAsyncResult ar)
{
AsyncResult result = (AsyncResult)ar;
MethodInvoker invoker = (MethodInvoker)result.AsyncDelegate;
invoker.EndInvoke(ar);
// GC.Collect();
}
private void LoadFile()
{
byte[] fileBytes = File.ReadAllBytes(@"c:\50mb.pdf");
// Third party OCX component for viewing PDF files.
this.pdfOcxViewer.OpenBuffer(fileBytes, fileBytes.Length, "");
this.pdfOcxViewer.CloseFile();
}
}