C# how to wait for a webpage to finish loading before continuing

后端 未结 11 1266
暖寄归人
暖寄归人 2020-11-27 03:33

I\'m trying to create a program to clone multiple bugs at a time through the web interface of our defect tracking system. How can I wait before a page is completely loaded

11条回答
  •  抹茶落季
    2020-11-27 03:36

    Best way to do this without blocking the UI thread is to use Async and Await introduced in .net 4.5.
    You can paste this in your code just change the Browser to your webbrowser name. This way, your thread awaits the page to load, if it doesnt on time, it stops waiting and your code continues to run:

    private async Task PageLoad(int TimeOut)
        {
            TaskCompletionSource PageLoaded = null;
            PageLoaded = new TaskCompletionSource();
            int TimeElapsed = 0;
            Browser.DocumentCompleted += (s, e) =>
            {
                if (Browser.ReadyState != WebBrowserReadyState.Complete) return;
                if (PageLoaded.Task.IsCompleted) return; PageLoaded.SetResult(true);
            };
            //
            while (PageLoaded.Task.Status != TaskStatus.RanToCompletion)
            {
                await Task.Delay(10);//interval of 10 ms worked good for me
                TimeElapsed++;
                if (TimeElapsed >= TimeOut * 100) PageLoaded.TrySetResult(true);
            }
        }
    

    And you can use it like this, with in an async method, or in a button click event, just make it async:

    private async void Button1_Click(object sender, EventArgs e)
    {
       Browser.Navigate("www.example.com");
       await PageLoad(10);//await for page to load, timeout 10 seconds.
       //your code will run after the page loaded or timeout.
    }
    

提交回复
热议问题