简体   繁体   English

在等待同一行代码时,在主线程webBrowser_DocumentCompleted中保持UI响应

[英]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. 我想在webBrowser1_DocumentCompleted事件中等一段时间。 The reason is so that Webbrowser Document stream is well downloaded when next document is completed. 原因是当下一个文档完成时,Webbrowser文档流可以很好地下载。 I don't want to block the UI when i am waiting and i don't want upcomming Document_Completed_Events to be fired. 我不想在等待时阻止用户界面,我不希望上传Document_Completed_Events。

 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. 问题是,当它在DocumentCompletedEvent中时,tick会停止.Kindly帮助我理解问题以及处理这些情况的好方法。

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. 更新:此技术通过分离预期的不需要的事件并转到DoEvents()来工作。它还将保持UI响应以及计时器滴答。

    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? 你使用Windows.Forms.Timer吗? You should know, what Windows.Forms.Timer executes in same thread with UI. 您应该知道,Windows.Forms.Timer在与UI相同的线程中执行什么。 So then you call Task.WaitAny you block thread and your timer stop worked. 那么你调用Task.WaitAny你阻止线程,你的计时器停止工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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