MongoDB CountAsync 和 Cursors 在新驱动程序的 Windows 服务中不工作

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

我有一个 Windows 服务,它从 SQL 服务器读取数据并将它们写入 MongoDB。

我正在尝试使此服务适应新的 MongoDB 驱动程序(使用 2.0.1 版本),但我遇到了一些问题。

我有这个:

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

此代码调用此方法。

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

现在的问题是:每次我在 mongo.UpdateExternalPage()

上调用这一行
var count = await collection.CountAsync(new BsonDocument());

方法退出而不处理下一条指令。

如果我执行这一行也会发生同样的事情:

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

但是如果我使用 Windows Forms 应用程序做同样的事情,就没有问题了!但是我需要这段代码在 Windows 服务中工作。有人知道我的实现是错误的还是使用新的 MongoDB 驱动程序有一些限制?

此问题与同步上下文和 async/avoid 方法的问题有关。
您有 运行 长 运行ning 任务的地方,应该替换此代码。
Use one of this approaches for running background task 由 Scott Hanselman 描述。

您可以快速检查并至少确定下一个问题的根源:

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

并将避免替换为任务 - public async Task UpdateExternalPage()

我将代码更改为以下内容:

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

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

它按预期工作。

同理,我把它改成:

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