简体   繁体   中英

Keep the UI responsive in main thread, webBrowser_DocumentCompleted while waiting on the same line of code

I want to wait some time in webBrowser1_DocumentCompleted Event. The reason is so that Webbrowser Document stream is well downloaded when next document is completed. I don't want to block the UI when i am waiting and i don't want upcomming Document_Completed_Events to be fired.

 private void FormTimer()
    {
        webBrowser1.Navigate("http://www.rolex.com/");
        webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
    }
    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        DownloadCount++;
        alarmCounter = 0;
        Task abc = new Task(() =>
        {
            while (alarmCounter < 5)
            {
                Thread.Yield();
            }
        });
        abc.Start();
        Task.WaitAny(abc);
    }

    void timer_Tick(object sender, EventArgs e)
    {
        alarmCounter++;
    }

The problem is that tick stops as it goes in DocumentCompletedEvent.Kindly help me understand the problem as well as a good approach to deal with these soughts of situations.

Update: This technique works ,by detaching the expected unwanted events and go for DoEvents() It will also keep the UI responsive as well as timer tick.

    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        richTextBox1.Text += "\nDocument Started" + documentCount;
        alarmCounter = 0;
        timer.Enabled = true;
        //Do some work
        webBrowser1.DocumentCompleted -= webBrowser1_DocumentCompleted;
        while (alarmCounter < 3)
        {
            Application.DoEvents();            
        }
        webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;             
        richTextBox1.Text += "\nDocument Completed." + documentCount;
    }

Are you use Windows.Forms.Timer? You should know, what Windows.Forms.Timer executes in same thread with UI. So then you call Task.WaitAny you block thread and your timer stop worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM