Lourival Lima Jr
Lourival Lima Jr

Reputation: 21

MongoDB CountAsync and Cursors not working in a Windows Service with the new driver

I have a Windows Service that reads data from a SQL Server and write them on MongoDB.

I'm trying to adapt this service to the new MongoDB driver (using 2.0.1 version), but I'm facing some problems.

I have this:

 protected void OnStart(string[] args)
    {
        threadExternalPage = new Thread(new ThreadStart(FacadeFactory.GetLivePrice.UpdateExternalPage));

This code calls this method.

 public async void UpdateExternalPage()
    {
        while (true)
        {
            MongoUpdateProductBO mongo = new MongoUpdateProductBO();
            await mongo.UpdateExternalPage();
        }
    }

Now the problem: everytime I call this line on mongo.UpdateExternalPage()

var count = await collection.CountAsync(new BsonDocument());

The method exits without processing the next instructions.

The same thing happens if I execute this line:

using (var cursor = await collection.Find(filter).ToCursorAsync())

But if I do the same thing using a Windows Forms application, there's no problem! But I need this code working in a Windows Service. Does somebody know if I the implementation is wrong or if there's some restriction using new MongoDB driver?

Upvotes: 1

Views: 1270

Answers (2)

Lourival Lima Jr
Lourival Lima Jr

Reputation: 21

I changed the code to the following:

 var cursor = collection.Find(filter).ToCursorAsync();
        cursor.Wait();

        using (cursor.Result)
        {
            while (cursor.Result.MoveNextAsync().Result)
            {

And it worked as expected.

In the same way, the count works when I change it to:

        var temp = collection.CountAsync(new BsonDocument());
        temp.Wait();
        var count = temp.Result;

Upvotes: 1

rnofenko
rnofenko

Reputation: 9533

This issue is related to problem with Synchronization context and async/avoid methods.
You have place where you run long running task, this code should be replaced.
Use one of this approaches for running background task described by Scott Hanselman.

You can fast check and at least be sure in source of problem next way:

protected void OnStart(string[] args)
{
     ThreadPool.QueueUserWorkItem(async x => await UpdateExternalPage();
}

And replace avoid to Task - public async Task UpdateExternalPage().

Upvotes: 0

Related Questions