如何在C#的控制台应用程序中使用带有Web浏览器的计时器?

如何在C#的控制台应用程序中使用带有Web浏览器的计时器?

问题描述:

我正在尝试一个接一个地加载多个url并且我正在使用timer.tick函数,以便在网页中加载所有ajax数据。



1.但是问题是控制台应用程序在计时器间隔之后调用timer.tick之前关闭因为计时器是新线程吗?



注意****:我也在使用[ STAThread] for main方法因为如果我不使用它会显示关于.pdb文件没有加载的警告



2.这里[STAThread]的作用是什么?



如何解决这个问题。有没有办法让它等到计时器停止。以下是代码示例。



I am trying to load multiple url's one after another and I am using timer.tick function so that all ajax data loads in the webpage.

1. But problem is that console application closes before timer.tick is call after interval of timer because timer is of new thread?

Note****: I am also using [STAThread] for main method because if I dont use it it showing an warning regarding .pdb file not loaded

2. What is the role of [STAThread] here?

How to solve this problem. Is there any way to make it wait till timer is stopped. Here is code samples below.

static void Main(string[] args)
    {
        OpenURLInBrowser("https://www.google.co.in/");
    }
private static void OpenURLInBrowser(String url)
    {
        if (!url.StartsWith("http://") && !url.StartsWith("https://"))
        {
            url = "http://" + url;
        }
        try
        {
            webbrowser.AllowNavigation = true;
            webbrowser.ScriptErrorsSuppressed = true;
            webbrowser.Navigate(new Uri(url));
            WaitTillPageLoadsCompletly(DynamicWebBrowser.webbrowser);
            timer.Interval = 10000;
            timer.Tick += Timer_Tick;
            timer.Start();
        }
        catch (UriFormatException)
        {
            return;
        }
    }
    private static void Timer_Tick(object sender, EventArgs e)
    {
        if (webbrowser.ReadyState == WebBrowserReadyState.Complete)
        {
            HtmlElement element = webbrowser.Document.GetElementById("loadingDiv");
            if (element != null)
            {
                Console.Write(element.OuterHtml + "\n\n\n");
                Console.WriteLine("==============================================================================================================" + "\n\n\n");
                timer.Stop();
                int count = 0;
                while (count < 2)
                {
                    OpenURLInBrowser("https://www.google.co.in/");
                    count++;
                }
            }
        }
    }
private static void WaitTillPageLoadsCompletly(WebBrowser webBrControl)
    {
        WebBrowserReadyState loadStatus;
        int waittime = 20000;
        int counter = 0;
        while (true)
        {
            loadStatus = webBrControl.ReadyState;
            Application.DoEvents();
            if ((counter > waittime) || (loadStatus == WebBrowserReadyState.Uninitialized) || (loadStatus == WebBrowserReadyState.Loading) || (loadStatus == WebBrowserReadyState.Interactive))
            {
                break;
            }
            counter++;
        }
        counter = 0;
        while (true)
        {
            loadStatus = webBrControl.ReadyState;
            Application.DoEvents();
            if (loadStatus == WebBrowserReadyState.Complete && webBrControl.IsBusy != true)
            {
                break;
            }
            counter++;
        }
    }





我的尝试:



以上代码就是我试过的。



What I have tried:

The above code is what I tried.

是的,你的代码没有STA线程。如果你把计时器放到你的html加载时间,当你使用文档完成事件时不需要这个



请试试这个



Yes, your code don't have STA thread. if you putting timer to get time for your html loading, that is not required when you use document completed event

Please try this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program
    {

        public static void Main(string[] args)
        {
            string url = "https://www.google.co.in/";
            Thread thread = new Thread(delegate ()
             {
                 using (WebBrowser browser = new WebBrowser())
                 {
                     browser.ScrollBarsEnabled = false;
                     browser.AllowNavigation = true;
                     browser.Visible = true;
                     browser.Navigate(url);
                     browser.Width = 1024;
                     browser.Height = 768;
                     browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentCompleted);


                     while (browser.ReadyState != WebBrowserReadyState.Complete)
                     {
                         System.Windows.Forms.Application.DoEvents();
                     }
                 }
             });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            Console.ReadKey();
        }


        public static void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser webBrControl = sender as WebBrowser;
            if (webBrControl.ReadyState == WebBrowserReadyState.Complete)
            {
                HtmlElement element = webBrControl.Document.GetElementById("prm");
                if (element != null)
                {
                    Console.Write(element.OuterHtml + "\n\n\n");
                    Console.WriteLine("==============================================================================================================" + "\n\n\n");
                }
            }
        }
    }
}


你不仅没有STA线程,你也没有消息泵,没有它,WebBrowser控件将无法正常工作。



参见 this [ ^ ]。
Not only do you not have an STA thread, you also do not have a message pump, without which the WebBrowser control will not work correctly.

See this[^].