VARUN NAYAK
VARUN NAYAK

Reputation: 666

How to wait for some second before next line executed

I want to show a MessageBox right after the webpage is completely loaded in my Winforms WebControl.

I used this code to delay:

System.Threading.Thread.Sleep(4000);
Task.Delay(2000);  

None of these is working. The problem is I got an infinite loop.

Can someone give me a solution or any better alternatives (if any) ?

Here is my code

private void btnGo_Click(object sender, EventArgs e)
{
    try
    {
        string WebPage = txtURL.Text.Trim();
        Webcntrl.Navigate(WebPage);   // Webcntrl is Name of  webcontrol in my  Windows Applications

        while (Webcntrl.ReadyState.ToString() != "Complete")
        {
            //System.Threading.Thread.Sleep(4000);
            //Task.Delay(2000);
        }
        MessageBox.Show("hI ! website loaded Sucessfully");
    }
    catch (Exception ex)
    {

    }
}

as per Ahmed ilyas suggested I modified code as per below

 private void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                string WebPage = txtURL.Text.Trim();
                Webcntrl.Navigate(WebPage);   // Webcntrl is Name of  webcontrol in my  Windows Applications

                Webcntrl.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(SiteLoaded);


            }
            catch (Exception ex)
            {

            }


        }

        private void SiteLoaded(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            MessageBox.Show("hI ! website loaded Sucessfully");         

        }

But now , message pop up multiple times.

Upvotes: 0

Views: 1251

Answers (1)

Ahmed ilyas
Ahmed ilyas

Reputation: 5822

you should be using the Web browser control's documentcomplete event:

http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documentcompleted(v=vs.110).aspx

this notifies you when the page has been finished loading. What you are doing is going into a while loop and holding up the thread that the browser control is executing on therefore nothing will "work" even when you put in a thread sleep (which BTW is not recommended to do regardless)

Upvotes: 1

Related Questions