How to handle a System.CannotUnloadAppDomainException?

I have a custom control with a Microsoft ReportViewer control. When the form is active with this custom control, and I exit the application by clicking the red cross (in the upper right corner), I get a System.CannotUnloadAppDomainException .

I read that this is a known bug in the MS ReportViewer control. To eliminate this exception, you need to call the ReleaseSandboxAppDomain method. I tried this, but it cannot make it work. I call this method in the ParentForm_Closing event in the user control. But this event does not fire when you close the application by clicking the red cross in the upper right corner.

So my question is: how can I prevent this exception from being displayed?

Here is the code that calls the ReleaseSandboxAppDomain method:

 this.ParentForm.FormClosing += delegate { reportViewer.LocalReport.ReleaseSandboxAppDomain(); }; 
+4
source share
1 answer

The fact that your ParentForm is inside the panel is definitely your problem.

If I understand your case, you have the following controls / forms:

  • MainForm is the main form of your application.
  • Panel1 - a panel that is a control inside MainForm
  • TheParentForm is a form inside Panel1 (with TopLevel as false)
  • UserControl1 is a usercontrol inside TheParentForm
  • ReportViewer is Microsoft user control inside UserControl1

When you close MainForm , TheParentForm does not close because it is not a top-level form. What you can do is add the following code to MainForm n in the FormClosing event FormClosing :

 private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { foreach (Control ctrl in this.Panel1.Controls) { Form ctrlAsForm = ctrl as Form; if (ctrlAsForm != null) { ctrlAsForm.Close(); } } } 

This will go through all the controls inside Panel1 and try to call the Close() method explicitly if the control is a form. Thus, closing the main form will also close the forms without the top level, which are inside Panel1 .

Now, as you wrote in UserControl1 :

 this.ParentForm.FormClosing += delegate { reportViewer.LocalReport.ReleaseSandboxAppDomain(); }; 

everything should be OK; when TheParentForm is closed, you can clean up and avoid your exception.

+5
source

Source: https://habr.com/ru/post/1393717/


All Articles