如何处理WebBrowser控件的线程 [英] How to Handle Threading for WebBrowser Control

查看:90
本文介绍了如何处理WebBrowser控件的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用BrowserControl导航到站点上的网页范围,然后解析html并提取有关书籍等的信息…我遇到与线程相关的问题(我认为)…

I am using BrowserControl to navigate to range of web pages on a site and then parse the html and extract information about books etc… I am having problems related (I think) to threading…

我有这样的东西.

// MAIN LOOP
for (int i = 0; i < NumberOfPages; i++)
 {
  WebBrowser.Navigate("http://AWebSite/" + NumberOfPages.ToString());
 }

// HANDLE ON_LOADED EVENT
 void WebBrowser_LoadCompleted(object sender, NavigationEventArgs e)
    {
   // Retrieve HTMLDocument, Parse it etc
    }

现在,由于控件导航到页面后事件触发需要花费几秒钟的时间,因此我有以下两种选择之一:

Now since it takes a few seconds for the event to fire after the control navigates to a page, I have one of two options:

OPTION1 在我的主循环中等待几秒钟,就像这样:

OPTION1 Wait a few seconds in my main loop, like this:

for (int i = 0; i < NumberOfPages; i++)
{
  WebBrowser.Navigate("http://www.mysite.com"); 

// wait for 5 seconds
DateTime wait = new DateTime();
while (new DateTime().Ticks < wait.Ticks + 5000)  
    {
     // not sure if I need do events here         
    }
}

OPTION2 另一个想法是将全局变量作为(布尔值)标志来指示事件处理程序该页面仍在下载中(该标志在主外观中设置为忙,然后重置,然后在处理返回的html之后重置).

OPTION2 Another idea is to a Global Variable as a (Boolean) Flag to indicate to the event handler that the page is still downloading (the flag is set to busy in the main look and then reset and then reset after after handling the html returned).

我觉得这两种方法都很笨拙,实际上,还有更好的方法是以某种方式处理这两件事(在不同的线程上运行?)

I have a feeling both of these approaches are clumsy and really that there is a better way is to somehow handle these two things (running on different threads?)

推荐答案

是的,延迟很笨拙-它可能需要更长的时间.

Yeah, a delay is clumsy - it may take longer than that or whatever.

您需要WebBrowser控件吗?看来您正在执行批处理.如果是这样,System.Net.WebClient可能会为您工作.它具有阻塞和异步方法-.DownloadData和.DoanloadDataAsync.

Do you need the WebBrowser control? It looks like you're doing some batch processing. If that's so, the System.Net.WebClient may work for you. It has blocking and asynchronous methods - .DownloadData and .DoanloadDataAsync.

如果需要的话,我可能可以挖掘一些代码,但是快速搜索可以找到其中的一些示例.

I can probably dig up some code if you need it, but a quick search shows some examples out there.

这篇关于如何处理WebBrowser控件的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆