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

标签 c#

我正在构建一个爬虫,我正在使用 aBot去做吧。这是一个非常好的系统:) 在开发过程中,我发现一个问题与我想如何构建我的爬虫比 aBot 项目本身更相关,但我希望你能帮助我。

我在设置爬虫的时候,指定了爬虫完成后调用的方法,有sync和async选项。

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

我想使用异步的,因为那样我会在处理旧的 url 时抓取另一个 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();
}

关于c# - 如何在关闭应用程序之前等待异步事件完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19815353/

相关文章:

c# - 如何将列表转换为数据表

c# - 在 richtextbox 中突出显示单词

c# - 在 ASP.Net Core 中使用分页传递模型参数

c# - FileStream - "The given path' 格式不受支持”

c# - 将正则表达式转换为 SQL

c# - Windows Phone 8 Geolocator 缓存位置

c# - 在 LINQ 中列出列

c# - 使用 Console.CursorLeft 进行控制台重定向

c# - 如何在 LINQ 表达式中预设变量?

c# - .NET 字典 : get or create new