7

forループがあります:

for (i = 0; i <= 21; i++)
{
  webB.Navigate(URL);
}

webBは webBrowser コントロールでiあり、int です。

ブラウザがナビゲートを完了するのを待ちたい。

しかし、これを見つけました:

  • API やアドインを使用したくない
  • この回答voidで示唆されているように、別の機能を使用できません

forループ中に待機する方法はありますか?

4

7 に答える 7

7

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());
}

ここで同様の質問に答えました。

于 2013-08-19T02:43:36.950 に答える
2

void別の機能を使用する必要はありません。単純に次のlambdaように使用します。

webB.DocumentCompleted += (sender, e) =>
{
    // your post-load code goes here
};
于 2013-08-19T00:11:10.417 に答える
1

適切な方法は、イベントを使用することです。
あなたのループでは、ナビゲーションが完了したことをどのように知ることができますか? ループから外れているかもしれませんが、まだ道半ばです...

また、待機中のループはビジー待機と呼ばれ、 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...
}
于 2013-08-19T03:45:44.660 に答える
0
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
于 2015-11-16T01:32:03.667 に答える