最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】C#中的WebBrowser的DocumentCompleted被调用两次

C# crifan 6267浏览 0评论

【问题】

C#中,用到WebBrowser,在DocumentCompleted事件中执行一些动作。

现在发现一个问题,有时候DocumentCompleted会被执行2次。甚至多次。

【解决过程】

1.参考:

Why is WebBrowser_DocumentCompleted() firing twice?

去添加判断:

private void wbsChaseFootprint_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    if (wbsChaseFootprint.ReadyState != WebBrowserReadyState.Complete)
    {
        //not actually complete, do nothing
        return;
    }
    
    //do things
    //...
}

然后调试一下,看看是否会发生该情况,断点是否能执行到该句。

结果不会执行到return;,但是DocumentCompleted还是被执行2次。

2.参考:

WebBrowser DocumentCompleted event fired more than once

去试试:

private void wbsChaseFootprint_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    //if (wbsChaseFootprint.ReadyState != WebBrowserReadyState.Complete)
    //{
    //    //not actually complete, do nothing
    //    return;
    //}

    if (!e.Url.Equals(wbsChaseFootprint.Url))
    {
        //not actually complete, do nothing
        return;
    }
    //do things
    //...
}

结果是,最后是可以了。

因为,对于另外一次的DocumentCompleted调用,传入的url,是和当时设置的url不同的,所以可以忽略掉。

3.但是稍微有点奇怪的是,当时设置的url是url1,然后接着,第一次调用DocumentCompleted时,已经就是url1了。

然后接着第二次的调用DocumentCompleted,传入的是url2。

觉得有点奇怪的是,应该是先url2,再url1才对啊。

 

【总结】

目前就用:

    if (!e.Url.Equals(wbsChaseFootprint.Url))
    {
        //not actually complete, do nothing
        return;
    }

的方法凑合用吧。

转载请注明:在路上 » 【已解决】C#中的WebBrowser的DocumentCompleted被调用两次

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.151 seconds, using 22.05MB memory