Question

I'm implementing PubSub using MongoDB. If I create my query specifying a TailableCursor with NoCursorTimeout:

using(var enumerator = _Collection.FindAs<BsonDocument>(Query.GTE("CreationTimeUTC", DateTime.UtcNow))
    .SetFlags(QueryFlags.AwaitData | QueryFlags.NoCursorTimeout | QueryFlags.TailableCursor)
    .SetSortOrder(SortBy.Ascending("$natural")).GetEnumerator))
{
    while(true)
    {
        if(enumerator.MoveNext())
        {
             //process the message here
        }
    }
}

MoveNext() blocks indefinitely (or until data is available or an error occurs). If I want to force MoveNext() to return (for instance, if I want to cancel listening) how do I do it? Call Dispose() on the enumerator or the cursor?

Was it helpful?

Solution

If you don't set a timeout on the cursor then that's pretty much all you can do, as long as the MoveNext method doesn't accept a CancellationToken. Just dispose of the enumerator, catch the ObjectDisposedException and move on.

I have a solution example for a similar case here. Which in this case would be:

try
{
    using(enumerator.CreateTimeoutScope(TimeSpan.FromHours(1)))
    {
        while(true)
        {
            if(enumerator.MoveNext())
            {
                 //process the message here
            }
        }
    }
}
catch (ObjectDisposedException)
{
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top