[英]How to use timer with web-browser in console application in c#?
我試圖一個接一個地加載多個URL,並且我使用timer.tick函數,以便將所有ajax數據加載到網頁中。
注意****:我也將[STAThread]用於主要方法,因為如果不使用它,它會顯示有關未加載.pdb文件的警告
如何解決這個問題呢。 有什么辦法讓它等到計時器停止。 這是下面的代碼示例。
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++;
}
}
static void Main(string[] args)
{
OpenURLInBrowser("https://www.google.co.in/");
Console.ReadKey();
}
您可以使用Console.ReadKey()或Console.ReadLine()停止控制台應用程序退出
您正在以錯誤的方式進行操作。 您不應該生成一個進程(在本例中為WebBrowser控件),然后進入緊密循環檢查其狀態是否更改。
而是,開始頁面加載,並將代碼綁定到WebBrowser控件的DocumentCompleted事件。 這樣,當瀏覽器完成頁面加載后,它將執行完成代碼(可以加載下一頁,或您要執行的任何操作),而無需坐在循環中監視它,這只是浪費資源。
請參閱: https : //msdn.microsoft.com/zh-cn/library/system.windows.forms.webbrowser.documentcompleted(v=vs.110).aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.