Is it possible to test if a WebBrowser.Document has been disposed so that I don't keep getting ObjectDisposedException's?
I know the following code will do the job, but I'd prefer to test for the Document being disposed rather than having to catch it. Any thoughts?
private Size GetContentSize()
{
try
{
if (
this.webBrowser.Document != null
&&
this.webBrowser.Document.Body != null)
{
return this.webBrowser.Document.Body.ScrollRectangle.Size;
}
else
{
return Size.Empty;
}
}
catch (ObjectDisposedException)
{
return Size.Empty;
}
}
The ObjectDisposedException is thrown when the WebBrowser instance is no longer valid. So checking the document will still cause the ObjectDisposedException to be thrown as the WebBrowser instance is already disposed...Either way you should have the Catch in your code to be sure that the object was not disposed between the check and return...
Hold on a minute. The fact that you are asking the question indicates a fundamental flaw in your design. Why are you holding on to an object that could possibly already be disposed? That is the problem. You should not need an answer to the question "how do I know if it has been disposed?" If you have a reference to the object, then it hasn't been disposed. If you've disposed it, then you should have thrown away all your references to it.
Conversely, if someone else has a reference and does not know that you've disposed it, then you shouldn't have disposed it, the code that is still using the object has the responsibility for disposing it.
What you need is a contract that describes who owns this object and when they will dispose it, and then implement that contract. If you do that, then you'll know whether the object has been disposed, and the exception will indicate a bug that is a violation of the contract.
Here's an article I wrote on a related problem a while back:
http://blogs.msdn.com/b/ericlippert/archive/2008/09/08/high-maintenance.aspx
The type of WebBrowser.Document is HtmlDocument. It doesn't have a Dispose() method.
The more likely source of the exception is the WebBrowser itself. It has an IsDisposed property that you could use. However, I'd strongly recommend you go looking for the bug in the code instead of applying that bandaid. Perhaps a stray using statement.