MongoDB c# 2.0.1 driver- connection suddenly closes

喜欢而已 提交于 2019-12-12 03:20:16

问题


Here's the full program code: (Except for Follower class which is only id and username - Json-type class) I don't have any users for db - just created simple collection

class Program
{
    static void Main(string[] args)
    {
        DBClass db = new DBClass();
        db.check();
    }
}

class DBClass
{
    protected string connectionString ="mongodb://localhost:27017";
    protected IMongoClient _client;
    protected IMongoDatabase _database;
    protected IMongoCollection<Follower> collection;

    public DBClass()
    {
        _client = new MongoClient(connectionString);
        _database = _client.GetDatabase("FollowedUsers");
        collection = _database.GetCollection<Follower>("UserData");
    }

    public async void  check()
        {
        var filter = Builders<Follower>.Filter.Eq("id", "266663861");
        var result = await collection.Find(filter).CountAsync();
        Console.WriteLine(result);
        Console.ReadLine();
    }

}

}

This is what I see in mongod:

2015-10-06T12:08:24.119+0300 I NETWORK  [initandlisten] connection
 accepted  from 127.0.0.1:50069 #2 (1 connection now open)
 2015-10-06T12:08:24.243+0300 I NETWORK  [conn2] end connection
 27.0.0.1:50069 (0 connections now open)

when I run it from VS it just terminates, throws no exceptions, this is what I see in the output The program '[11724] MongoTest.vshost.exe' has exited with code 0 (0x0). When I debug it I see that it terminates on this line:

var result = await collection.Find(filter).CountAsync();

Did I configure smth incorrectly?


回答1:


Your problem is not related to MongoDB. Reason of problem is main thread closes mongoDb connection while dbCheck is being executed.

You should change next rows:
1)

public async Task check()

2)

db.check().Wait();



来源:https://stackoverflow.com/questions/32966361/mongodb-c-sharp-2-0-1-driver-connection-suddenly-closes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!