MongoDB Driver 2.0 C# is there a way to find out if the server is down? In the new driver how do we run the Ping command?

前端 未结 3 1614
南方客
南方客 2021-01-17 22:59

How do you call the Ping command with the new C# driver 2.0?
In the old driver it was available via Server.Ping()? Also, Is there a way to find

3条回答
  •  孤城傲影
    2021-01-17 23:23

    As @i3arnon's answer I can tell it was reliable for me in this way:

    var server = client.Cluster.Description.Servers.FirstOrDefault();
    var serverState = ServerState.Disconnected;
    if (server != null) serverState = server.State;
    

    or in new versions of .Net

    var serverState = client.Cluster.Description.Servers.FirstOrDefault()?.State 
        ?? ServerState.Disconnected;
    

    But if you realy want to run a ping command you can do it like this:

    var command = new CommandDocument("ping", 1);
    try
    {
        db.RunCommand(command);
    }
    catch (Exception ex)
    {
        // ping failed
    }
    

提交回复
热议问题