Why a RaceOnRCWCleanup error when closing a form with WebBrowser control on it?-Collection of common programming errors
It is not an error, it is a warning. Produced by a Managed Debugging Assistant (MDA), an extension to the debugger for managed code, that thinks it is seeing something going wrong in your code. The shoe fits. You are using an RCW, WebBrowser is an COM control. You are killing off the RCW, you are closing your form. The MDA steps in because it thinks it is seeing the web browser in use and it getting killed before the request is completed. That would normally only make sense if you are using a thread in your code.
Are you? If not, don’t lose any sleep over it. COM uses reference counting, notorious for not being able to resolve circular references.
Okay, I got a repro for this, enabled by the comments. Yes, this is triggered by the form’s CancelButton property or the button’s DialogResult property. This happens when the WB has the focus, it sees the Escape key press. Part of the ActiveX plumbing is to tell the container about it so it can respond to keystrokes that should have a side-effect. Shortcut keystrokes, Tab, Enter. And Escape. If the button then closes the form, the debugger sees the WB getting disposed while there are active stack frames from the RCW code on the stack. The danger is that this might cause a crash when the called code returns since the COM component got released, it isn’t uncommon.
Seeing this crash is pretty unlikely, but I can imagine that this could bomb when the finalizer thread runs just before the button’s Click event returns. The workaround for the MDA and the potential crash is to delay closing the form until after the ActiveX code stops running. Elegantly done with Control.BeginInvoke(). Like this:
private void CancelButton_Click(object sender, EventArgs e) {
this.BeginInvoke((MethodInvoker)delegate { this.Close(); });
}