STA线程中的c#Web浏览器控制消耗大量使用

时间:2017-06-03 03:46:31

标签: c# .net multithreading

我试图在c#代码中模拟一个Web浏览器,因为url有javascript,我打算像100毫秒一样等他从中获取全部内容,最后,我们不能使用像web这样的方法客户端直接从它下载,所以我尝试使用网页浏览器来获取内容,以下是我的代码:

  var t = new Thread(() =>
            {
                while (true)
                {
                    connection = new SqlConnection(ConfigurationManager.AppSettings["connectionString"]);
                    connection.Open();
                    SqlCommand cmd = new SqlCommand("SELECT top 200 stock_code FROM update_stock_code", connection);
                    DataTable dt = new DataTable();
                    new SqlDataAdapter(cmd).Fill(dt);


                cmd = new SqlCommand("DELETE FROM update_stock_code where stock_code in (select TOP 200 * FROM update_stock_code)", connection);
                cmd.ExecuteNonQuery();
                for (int a = 0; a < dt.Rows.Count; a++)
                {
                    WebBrowser wb = new WebBrowser();
                    wb.DocumentCompleted += Wb_DocumentCompleted;
                    wb.ScriptErrorsSuppressed = true;
                    wb.Tag = dt.Rows[a][0].ToString();
                    wb.Navigate("URL");


                    System.Windows.Forms.Application.Run();
                }
                connection.Close();
                connection.Dispose();

                if (dt.Rows.Count == 0)
                {
                    Thread.Sleep(300000);
                }
            }
        });
        t.SetApartmentState(ApartmentState.STA);
        t.Start();


private static void Wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            var wb = (WebBrowser)sender;
            string content = wb.Document.Body.InnerHtml;
            long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

            while (wb.ReadyState != WebBrowserReadyState.Complete)
            {
                long milliseconds2 = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
                if (milliseconds2 - milliseconds > 100)
                {
                    //some code event
                    break;
                }
                System.Windows.Forms.Application.DoEvents();
            }
            System.Windows.Forms.Application.ExitThread();
            wb.Dispose();
            /* ... */
        }

但是,当我使用上面的代码时,它占用了我33%的处理器使用率,我正在尝试打开2个程序,它打了100%我的CPU,请问如何减少烧毁我的处理器之前的CPU使用率?我在代码上做错了吗?

0 个答案:

没有答案