永远迭代MongoDB游标块



我使用的是MongoDB C#驱动程序1.8.1.20和Mongo 2.4.3。我使用下面的无限循环来轮询来自有上限集合的新消息,并在消息到来时对其进行处理(使用可定制的游标并等待数据)。它在大多数情况下都有效,但在生产中,似乎不时会调用枚举器。MoveNext()阻塞并且从不返回。这导致循环暂停,并且我的应用程序不再接收更新。这似乎是在连接意外关闭时发生的。

while (true)
{
    try
    {
        using (MongoCursorEnumerator<QueueMessage> enumerator = GetCursor())
        {
            while (!enumerator.IsDead)
            {
                while (enumerator.MoveNext()) // This is blocking forever when connection is temporarily lost
                    this.processMessage(enumerator.Current);
            }
        }
     }
     catch (Exception ex)
     {
         Trace.TraceError("Error in the ReceiveCore loop:  " + ex.ToString());
     }
}

GetCursor函数的作用是:

cursor = (MongoCursorEnumerator<QueueMessage>)collection
    .FindAllAs<QueueMessage>()
    .SetFlags(QueryFlags.AwaitData | QueryFlags.TailableCursor | QueryFlags.NoCursorTimeout)
    .SetSortOrder(SortBy.Ascending("$natural"))
    .GetEnumerator();

为什么这种阻塞是永远的,当它不能完成时(可能是超时),我该怎么做才能确保它抛出异常?

我想我应该删除QueryFlags.NoCursorTimeout,然后让它偶尔超时,然后重新启动。

最新更新