繁体   English   中英

如何在关闭应用程序之前等待异步事件完成?

[英]How to wait for an async event to finish before closing the application?

我正在构建一个爬虫,并且正在使用aBot做到这一点。 这是一个非常好的系统:)在开发过程中,我发现一个问题与aBot项目本身相比,与我要如何构建搜寻器有关,但希望您能为我提供帮助。

设置搜寻器时,我指定了搜寻完成后要调用的方法,其中有同步和异步选项。

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

我想使用异步网址,因为那样的话,我将在处理较旧的网址时抓取另一个网址。 在我抓取最后一个URL之前,它可以正常工作。 搜寻最后一个网址时,我会调用completeAsync方法,并且搜寻器已经完成工作,因此它完成了并且程序关闭,而没有完全处理_ProcessPageCrawlComplete方法,因此,我不能保证会处理最后一个URL。

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

编辑:我忘了提及:我确实有权访问搜寻器代码。 我当前的解决方法是:如果链接是最后一个要处理的链接,请创建WaitHandle并等待其完成。 听起来有点混乱,但是...

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();
}

暂无
暂无

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

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