Search code examples
.netvb.netgarbage-collectiondispose

Correct Method for checking if an item has been disposed


What is the correct syntax in VB .net for checking that an object has been disposed of?

In my case, the public-declared database connection (dbLocal) is disposed of by a USING block and calling the database connection again triggers an error.

I've tried implementing the .IsDisposed code here but the declaration requires a Get, which i'm not entirely sure how to add.

Once I can check it .isdisposed, what is the correct method to recreate the public object?

DB Declaration:

Public dbLocal As New SQLiteConnection("Data Source=" & Replace(Application.StartupPath, "\", "\\") & "\\database.db;FailIfMissing=True")

USING loop:

Using dbLocal

'Create Command & add parameters
Dim Typecmd As New SQLiteCommand(TypeSQLI, dbLocal)
    With Typecmd.Parameters.Add("@id", DbType.String, 50, "id")
        Typecmd.Parameters.Add("@description", DbType.String, 100, "description")
        Typecmd.Parameters.Add("@sex", DbType.Int16, 1, "sex")
        Typecmd.Parameters.Add("@master", DbType.String, 50, "master")
        Typecmd.Parameters.Add("@size_min", DbType.String, 2, "size_min")
        Typecmd.Parameters.Add("@size_max", DbType.String, 2, "size_max")
        Typecmd.Parameters.Add("@size_half", DbType.Int16, 1, "size_half")
        Typecmd.Parameters.Add("@lining", DbType.String, 2, "lining")
    End With

Dim adapter As New SQLiteDataAdapter()
adapter.InsertCommand = Typecmd

Try
    Dim iRowsInserted As Int32 = adapter.Update(typetable)

    'Output result
    LstProcessed.Items.Add(iRowsInserted & " records added.")
    LstProcessed.TopIndex = LstProcessed.Items.Count - 1

    Catch ex As Exception
        MsgBox("Import error. " & Chr(13) & Chr(10) & "Check syntax of imported file (were there headers?).", MsgBoxStyle.Critical)
End Try

End Using

Ideally the 'IsDispose' function will check if the DB is closed before entering the USING loop.

I've added the IsDisposed declaration, as documented in the MSDN article, resulting in...

Public ReadOnly Property IsDisposed() As Boolean
    Get
        ???
    End Get
End Property

Solution

  • You shouldn't need to check for disposal of an object.

    You should ideally wrap it in a Using block like this:

    Using obj As New foo
        'use your object
    End Using
    

    Next time you use it wrap the code in another Using block.

    I think your issue is not creating a New object at the start of your Using block. You probably want this:

    Using dbLocal As New SQLiteConnection("Data Source=" & Replace(Application.StartupPath, "\", "\\") & "\\database.db;FailIfMissing=True")
        '...
    End Using
    

    Here the scope of dbLocal is only for the lifetime of the Using block. Currently you are using a global variable which is being disposed of at the End Using line.