【问题】
C#中,用到WebBrowser,在DocumentCompleted事件中执行一些动作。
现在发现一个问题,有时候DocumentCompleted会被执行2次。甚至多次。
【解决过程】
1.参考:
Why is WebBrowser_DocumentCompleted() firing twice?
去添加判断:
1 2 3 4 5 6 7 8 9 10 11 | 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
去试试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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才对啊。
【总结】
目前就用:
1 2 3 4 5 | if (!e.Url.Equals(wbsChaseFootprint.Url)) { //not actually complete, do nothing return ; } |
的方法凑合用吧。