Getting System.OutOfMemoryException when using ReportViewer contol in Local mode

PROBLEM:

========

  1. Consider you've a ASP.NET application that contains Report Viewer control (2005 / 2008) in Local Mode.
  2. You have an RDLC report file, that loads large amount of data / has lots of expressions. (Both are not recommended in Local mode)
  3. Everytime you refresh the web page, the Report Viewer stores objects in the session.
  4. The behaviour of Report Viewer storing objects in the session is by design.
  5. Each time the report viewer page is refreshed the complete report info object is added to session.
  6. These objects obviously gets deeply rooted in session and so Garbage collector never collects them untill the complete app unloads itself.
  7. And that is apparently going to increase the memory pressure in multiple folds, ending up with System.OutOfMemoryException.

WORKAROUND: (Please note: This doesn't guarantee to resolve the exception. The Out of Memory exception can be caused due to different reasons and the below workaround is for one such scenario, which can help to avoid this error to a certain extent. You should avoid using it at any given point of time and try to switch to the ExecuteReportInSandboxAppDomain mode)

===========

== In the page_load event, add this,

== VB.NET

If Session.Count > 0 Then

For i As Integer = 0 To Session.Count - 1

If Session(i).GetType().ToString() = "Microsoft.Reporting.WebForms.ReportHierarchy" Then

Session.RemoveAt(i)

End If

Next

End If

== C#,

if(Session.Count > 0)

{

for (int i = 0; i < Session.Count; i++)

{

if (Session[i].GetType().ToString() == "Microsoft.Reporting.WebForms.ReportHierarchy")

{

Session.RemoveAt(i);

}

}

}