C# - 如何在一段时间内阻止方法返回?

标签 c# asynchronous timer webbrowser-control

我有一个包含 Web 浏览器控件的 win 窗体应用程序。由于导航的异步性质,我需要能够在网络浏览器上的操作之间添加延迟。

Document_Complete 事件没有值(value),因为它没有考虑到一个页面可能包含多个 AJAX 请求。事件发生多次。

更新

AJAX 请求是在页面加载时发出的。因此,页面加载和某些 DIV 中的内容是通过 HTTP 请求获取的。因此,Document_Complete 事件在文档首次加载时引发,然后在每个 (AJAX) HTTP 请求返回时引发。没有布埃诺。

更新 2

我的应用程序尝试从 Webbrowser.Document 对象读取 HtmlElements。因为代码执行速度比 HTTP 请求返回更快...文档对象不包含所有 html 元素。

我需要的是一些方法来延迟主线程中方法的调用。我试过使用计时器:

private void startTimer()
        {
            timer.Interval = 2000;
            timer.Start();
            while (!BrowserIsReady)
            {
                //Wait for timer
            }
        }

这会锁定线程并且 tick 事件永远不会触发。这个循环永远不会结束。

我想运行一系列这样的方法:

Navagate("http://someurl.com");
//delay
ClickALink();
//delay
Navagate("Http://somewhere.com");
//delay

我可以用计时器和 BackgroundWorker 解决这个问题吗?有人可以提出可能的解决方案吗?

最佳答案

您可以考虑使用 Threading 命名空间中的 Monitor 类。示例如下。

using System;
using System.Threading;

namespace MonitorWait
{
    class Program
    {
        private static readonly object somelock = new object();

        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(SyncCall));

            Thread.Sleep(5000);  //Give the SyncCall a chance to run...
            //Thread.Sleep(6000);  //Uncomment to see it timeout.

            lock (somelock)
            {
                Monitor.Pulse(somelock);  //Tell the SyncCall it can wake up...
            }

            Thread.Sleep(1000);  //Pause the main thread so the other thread 
                                 //prints before this one :)

            Console.WriteLine("Press the any key...");
            Console.ReadKey();
        }

        private static void SyncCall(object o)
        {
            lock (somelock)
            {
                Console.WriteLine("Waiting with a 10 second timeout...");
                bool ret = Monitor.Wait(somelock, 10000);
                if (ret)
                {
                    Console.WriteLine("Pulsed...");
                }
                else
                {
                    Console.WriteLine("Timed out...");
                }
            }
        }
    }
}

关于C# - 如何在一段时间内阻止方法返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3551603/

相关文章:

c# - 什么时候应该将操作标记为异步?

javascript - Actionscript 2 Setinterval向计时器添加毫秒

java - 如何获取由 Swing 计时器每秒更新 3 次的 JFormattedTextField 的用户编辑值?

c - 在c中打印更新变量

c# - 在组合框中以其自己的样式显示字体样式

c# - 过滤掉重复字母并重新分配给菜单 alt 键可用字母的算法

c# - 统一掉落 Sprite

java - FileInputStream 在 .close() NPE 上崩溃

c# - 无法在 Windows XP 计算机上安装/卸载 Async CTP

python - 如何制作一组既可以同步又可以异步使用的函数?