如何在webBrowser上实现多线程

本文关键字:实现 多线程 webBrowser | 更新日期: 2023-09-27 18:14:11

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//list of tasks
}
private void webBrowser2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//list of tasks
}

见上图。我的问题是,如何使它们同时运行(使两个线程手动控制它们的监控),现在的问题是它们都在主线程上单独运行,我可以做其他任务,感谢帮助!对不起,我的英语不好

和我尝试使用的,例如:

    Thread threadw1 = new Thread(() => webBrowser1.Navigate("url1"));
    Thread threadw2 = new Thread(() => webBrowser2.Navigate("url2"));
    threadw1.Start();
    threadw2.Start(); 

但是那是使用线程来导航,一旦导航完成,那么系统就会单独运行完成的文档。我不知道如何控制他们,谢谢你的帮助!

我已经把任务包装在一个函数中,现在的问题是当我这样做时,它不起作用

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.ReadyState < WebBrowserReadyState.Complete) return;
                // Do the work, you have the event args in ev

            Thread wbb1 = new Thread(() => wb1task());
            wbb1.Start();
            //wb1task();
        }

,但当我这样做,它的工作,但它成为一个单一的线程:

 private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.ReadyState < WebBrowserReadyState.Complete) return;
                // Do the work, you have the event args in ev

            //Thread wbb1 = new Thread(() => wb1task());
           // wbb1.Start();
            wb1task();
        }

线程启动然后文档完成,我需要在wbb1.Start()之后保持一些东西;防止它跳出循环:)

好了,问题解决了,谢谢大家!

wbb1.SetApartmentState(ApartmentState.STA);

如何在webBrowser上实现多线程

将要运行的任务放在DocumentCompleted事件的处理程序中。我用了根线,因为你提到过。我建议使用ThreadPoolTask

private void webBrowser1_DocumentCompleted(object sender, 
        WebBrowserDocumentCompletedEventArgs e)
{
    new Thread((state) => {
        WebBrowserDocumentCompletedEventArgs ev = 
                (WebBrowserDocumentCompletedEventArgs) state;
        // Do the work, you have the event args in ev
    }) {Name = "Thread for webBrowser1"}.Start(e);
}