【发布时间】:2021-04-30 02:38:17
【问题描述】:
我是 C# 新手,我想创建一个 Windows 窗体应用程序,它显示(它必须是可见的!)一个带有一些信息和按钮的窗口,它还从 Internet 加载一个页面(使用 selenium 和 phantom.js -虽然它已被弃用)每分钟。我写了这样的东西:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using OpenQA.Selenium;
using OpenQA.Selenium.PhantomJS;
namespace WindowsFormsApplication1
{
public partial class Someclass : Form
{
private void label1_Click(object sender, EventArgs e)
{
}
private void Someclass_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// Shows some text "Hello friend"
MessageBox.Show("Hello friend!");
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello again", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public Someclass()
{
InitializeComponent();
while (!IsDisposed)
{
MessageBox.Show("Now the page will be downloaded");
var driverService = PhantomJSDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
using (var driver = new PhantomJSDriver(driverService))
{
driver.Navigate().GoToUrl("http://stackoverflow.com/");
MessageBox.Show("Here we are going to open StackOverflow");
var questions = driver.FindElements(By.ClassName("fs-display2"));
foreach (var question in questions)
{
// This will display some text from stackoverflow main page.
Console.WriteLine(question.Text);
question.Click();
MessageBox.Show("This is stackoverflow: " + question.Text);
}
MessageBox.Show("Here we go");
}
System.Threading.Thread.Sleep(60000); // delay in microseconds
}
}
}
我的问题是,如果我使用“while”,我的窗口不会出现(但来自互联网的页面会正确加载 - 每 1 分钟一次),如果我使用“if”而不是“while”,我的窗口会显示得很好,但是,当然,页面加载只进行一次。什么可以解决我的问题?
【问题讨论】:
-
该代码不能放在那里。当构造函数被调用时,表单仍然不存在。 InitializeCompoment 将开始创建包含在表单中的对象,但循环永远不会允许表单引擎完成将表单显示在屏幕上的工作。该代码可以作为按钮上的某些单击事件的事件处理程序插入。或放置在 BackgroundWorker DoWork 事件中或作为 Timer 对象的事件处理程序。
-
您很可能会通过不断在 UI 线程上执行该工作来阻止想要显示您的窗口的线程。它与 If 一起使用的原因是,一旦您完成下载,它就可以返回绘制您的 UI。 While 循环占据 UI 线程,从不将其返回给绘制内容
标签: c# selenium while-loop phantomjs