【问题标题】:How to wait for an async event to finish before closing the application?如何在关闭应用程序之前等待异步事件完成?
【发布时间】:2013-11-06 14:57:39
【问题描述】:

我正在构建一个爬虫,我正在使用aBot 来完成它。这是一个非常好的系统:) 在开发过程中我发现了一个问题,与我想如何构建我的爬虫而不是aBot项目本身有关,但我希望你能帮助我。

设置爬虫时,我指定爬取完成时调用的方法,有同步和异步选项。

        crawler.PageCrawlCompleted += crawler_ProcessPageCrawlCompleted;
        crawler.PageCrawlCompletedAsync += crawler_ProcessPageCrawlCompleted;

我想使用异步的,因为那样我会在处理旧的网址时抓取另一个网址。这工作正常,直到我抓取最后一个网址。 当我爬到最后一个时,我调用了 completeAsync 方法,我的爬虫已经完成工作,所以它完成并关闭程序,没有完全处理完 _ProcessPageCrawlComplete 方法,所以我不能保证最后一个 url 会被处理。

在关闭应用程序之前,我有什么方法可以等待最后一个事件完成?这是设计缺陷吗?

编辑:我忘了提:我确实可以访问爬虫代码。我目前的解决方法是:如果链接是最后一个要处理的链接,则创建一个 WaitHandle 并等待它完成。不过听起来有点乱……

【问题讨论】:

  • 这可能过于简单了,但您不能简单地记录打开的爬虫的数量,当您点击完成方法时减少该数量,直到该数量为 0 才关闭应用程序?
  • 很遗憾没有,爬虫会在获取到最后一页的最后响应时完成“爬取”。所以可能会发生爬虫关闭了,但是最后的结果还在处理中

标签: c#


【解决方案1】:

ManualResetEvent 可以是一种解决方案:

在你的调用方法中:

//Declare the reset event
ManualResetEvent mre = new ManualResetEvent(false);

//Call the async method and subscribe to the event 
crawler.PageCrawlCompletedAsync += crawler_ProcessPageCrawlCompleted;

//The application will wait here until the mre is set.
mre.WaitOne();

在您的事件处理程序中:

private void crawler_ProcessPageCrawlCompleted(...)
{
   ....
   mre.Set();
}

另一种方法是CountdownEvent。假设你需要爬取 10 个页面:

CountdownEvent countdown = new CountdownEvent (10);

//Subscribe to the event 
crawler.PageCrawlCompletedAsync += crawler_ProcessPageCrawlCompleted;

//Call 10 time the async method
....

//Wait for all events to complete
countdown.Wait();

在处理程序中:

private void crawler_ProcessPageCrawlCompleted(...)
{
    ....
   mre.Signal();
}

【讨论】:

  • 感谢@Alberto,这似乎是一个不错的方法,我会研究一下。但是如果我调用 crawler_ProcessPageCrawlCompleted 10 次,完成第一个处理将设置 ManualResetEvent,然后不需要最后一个来完成应用程序。这个说法正确吗?
  • 你应该只在最后一个事件中调用 mre.Set() ......我在答案中添加了另一种方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
  • 2021-09-08
相关资源
最近更新 更多