Is it possible to test if a WebBrowser.Document has been disposed so that I don't keep getting ObjectDisposedException's?

家住魔仙堡 提交于 2019-12-24 16:19:09

问题


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;
        }
    }      

回答1:


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.




回答2:


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




回答3:


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...



来源:https://stackoverflow.com/questions/4124833/is-it-possible-to-test-if-a-webbrowser-document-has-been-disposed-so-that-i-don

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!