使用Driver 2.0最佳实践连接到MongoDB服务器

时间:2015-04-25 12:30:25

标签: vb.net mongodb

我有连接到MongoDB的VB.net代码。当数据库启动并运行时,我的代码工作正常,但是当数据库没有运行时,我没有收到任何错误。

如何检查服务器是否已启动并运行,以便我可以连接到它并完成我的工作?基本上,如果服务器启动,ELSE会向用户返回一条消息,表明该服务器不可用。

我查看有关MongoClient类的文档,但我似乎无法找到任何可以使用的文档。

MongoClient类(http://api.mongodb.org/csharp/2.0/html/T_MongoDB_Driver_MongoClient.htm

以下是我的代码,用于连接到MongoDB:

Public Function DbConnection(ByRef ConnString As String, vDbName As String, vColName As String) As MongoClient

    'default port
    'ConnString = "mongodb://localhost:27017"

    'example DB and Collection
    'vDbName = "blog"
    'vColName = "users"

    'Root Object
    Dim vClient As MongoClient
    vClient = New MongoClient(ConnString)

    Dim vDb As MongoDatabaseBase
    vDb = vClient.GetDatabase(vDbName)

    Dim vCol As IMongoCollection(Of BsonDocument)
    vCol = vDb.GetCollection(Of BsonDocument)(vColName)

    Return vClient

End Function

下面是我使用InsertOneAsync而不会产生错误的附加代码:

Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If txtName.Text = "" Then
        MsgBox("Enter a Name for the Database.")
    Else

        Dim ConnString As String
        ConnString = txtConnStr.Text

        Dim vDbName As String
        vDbName = txtDb.Text

        Dim vColName As String
        vColName = txtColl.Text

        'Root Object
        Dim vClient As MongoClient

        vClient = DbConnection(ConnString, vDbName, vColName)

        Dim vDb As MongoDatabaseBase
        vDb = vClient.GetDatabase(vDbName)

        Dim vCol As IMongoCollection(Of BsonDocument)
        vCol = vDb.GetCollection(Of BsonDocument)(vColName)

        Dim vAddUser As BsonDocument
        vAddUser = New BsonDocument

        vAddUser.Add("_Id", txtID.Text)
        vAddUser.Add("Name ", txtName.Text)
        vAddUser.Add("Email", txtEmail.Text)
        vAddUser.Add("City", txtCity.Text)

        rtfDataDisplay.Text = "BsonDocument = " & vAddUser.ToString & ", #" & vAddUser.Count

        Await vCol.InsertOneAsync(vAddUser)

    End If
End Sub

以下是我提出的解决方案。我只发布了Try ... Catch,因为我已经发布了上面的整个程序。

        Try

            Dim watch As Stopwatch = New Stopwatch

            watch.Start()

            Dim insertResult As Task = vCol.InsertOneAsync(vAddUser)
            Await insertResult

            watch.Stop()

            MsgBox("Faulted =" & insertResult.IsFaulted.ToString & ", Status = " & insertResult.Status.ToString & ", Watch = " & watch.Elapsed.ToString)

        Catch ex As Exception
            If ex.HResult.ToString = "-2146233083" Then

                MsgBox("unable to insert data due to a timeout exception")
            Else
                MsgBox("Unable to insert data = " & ", HResult = " & ex.HResult.ToString & "!" & ex.ToString)
            End If

        End Try

1 个答案:

答案 0 :(得分:0)

由于asynch只返回Task,因此它不会等到操作完成。如果您在任务之后等待,那么您将捕获异常并相应地处理它,这是示例

改变这个 Var insertTask = vCol.InsertOneAsync(vAddUser); insertTask.Wait();

{{1}}

然后从button_click方法签名中删除async关键字。