Create the Webbrowser control in a separate thread
When trying to create a new webbrowser control from each URI in each URI, click a series of URLs, you may encounter a problem, that is, the thread ends before the document is fully loaded, so it will never trigger triggers DocumentComplete event.
In order to solve this problem, a STA (single -threaded unit) thread needs to be created to pump the message cycle. This provides a suitable environment for ActiveX components such as Webbrowser control. The following example code demonstrates how to achieve this:
In this code, create a new STA thread and assign it to the variable TH. SetapartmentState () method is used to specify that this thread will be STA thread. Subsequently, start the thread and call the Navigate () method on the br (webbrowser) instance to navigate to the required URL. Finally, register the documentCompleted event processing program and use Application.run () to start the message loop of the STA thread.
<code class="language-csharp">private void runBrowserThread(Uri url) { var th = new Thread(() => { var br = new WebBrowser(); br.DocumentCompleted += browser_DocumentCompleted; br.Navigate(url); Application.Run(); }); th.SetApartmentState(ApartmentState.STA); th.Start(); } void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { var br = sender as WebBrowser; if (br.Url == e.Url) { Console.WriteLine("已导航到 {0}", e.Url); Application.ExitThread(); // 停止线程 } }</code>
When the document is loaded, the browser_documentCompleted event processing program will be performed. It checks whether the loaded URL matches the target URL. If it matches, the navigation information is printed to the console and uses Application.exitthread () to terminate the thread.
The above is the detailed content of How to Prevent Thread Termination Before WebBrowser Control Document Completion?. For more information, please follow other related articles on the PHP Chinese website!