forループがあります:
for (i = 0; i <= 21; i++)
{
webB.Navigate(URL);
}
webB
は webBrowser コントロールでi
あり、int です。
ブラウザがナビゲートを完了するのを待ちたい。
しかし、これを見つけました:
- API やアドインを使用したくない
- この回答
void
で示唆されているように、別の機能を使用できません
forループ中に待機する方法はありますか?
WinFroms アプリケーションでホストすると仮定すると、パターンWebBrowser
を使用してループで簡単かつ効率的に実行できますasync/await
。これを試して:
async Task DoNavigationAsync()
{
TaskCompletionSource<bool> tcsNavigation = null;
TaskCompletionSource<bool> tcsDocument = null;
this.WB.Navigated += (s, e) =>
{
if (tcsNavigation.Task.IsCompleted)
return;
tcsNavigation.SetResult(true);
};
this.WB.DocumentCompleted += (s, e) =>
{
if (this.WB.ReadyState != WebBrowserReadyState.Complete)
return;
if (tcsDocument.Task.IsCompleted)
return;
tcsDocument.SetResult(true);
};
for (var i = 0; i <= 21; i++)
{
tcsNavigation = new TaskCompletionSource<bool>();
tcsDocument = new TaskCompletionSource<bool>();
this.WB.Navigate("http://www.example.com?i=" + i.ToString());
await tcsNavigation.Task;
Debug.Print("Navigated: {0}", this.WB.Document.Url);
// navigation completed, but the document may still be loading
await tcsDocument.Task;
Debug.Print("Loaded: {0}", this.WB.DocumentText);
// the document has been fully loaded, you can access DOM here
}
}
DoNavigationAsync
ここで、が非同期で実行されることを理解することが重要です。これを呼び出してForm_Load
完了を処理する方法は次のとおりです。
void Form_Load(object sender, EventArgs e)
{
var task = DoNavigationAsync();
task.ContinueWith((t) =>
{
MessageBox.Show("Navigation done!");
}, TaskScheduler.FromCurrentSynchronizationContext());
}
ここで同様の質問に答えました。
void
別の機能を使用する必要はありません。単純に次のlambda
ように使用します。
webB.DocumentCompleted += (sender, e) =>
{
// your post-load code goes here
};
適切な方法は、イベントを使用することです。
あなたのループでは、ナビゲーションが完了したことをどのように知ることができますか? ループから外れているかもしれませんが、まだ道半ばです...
また、待機中のループはビジー待機と呼ばれ、 CPU の負荷が高くなります。
ページの準備ができたときに通知を受け取り、その間に CPU を他のものに使用できるようにするには、@Jashaszun が提案したようにイベントを使用します。
void YourFunction()
{
//Do stuff...
webB.DocumentCompleted += (sender, e) =>
{
//Code in here will be triggered when navigation is complete and document is ready
};
webB.Navigate(URL);
//Do more stuff...
}
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("stackoverflow.com/")
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
------yourcode------
End Sub
End Class